/*
 * ******************************************************************************
 *  jquery.mb.components
 *  file: jquery.browser.js
 *
 *  Copyright (c) 2001-2013. Matteo Bicocchi (Pupunzi);
 *  Open lab srl, Firenze - Italy
 *  email: matteo@open-lab.com
 *  site: 	http://pupunzi.com
 *  blog:	http://pupunzi.open-lab.com
 * 	http://open-lab.com
 *
 *  Licences: MIT, GPL
 *  http://www.opensource.org/licenses/mit-license.php
 *  http://www.gnu.org/licenses/gpl.html
 *
 *  last modified: 16/01/13 20.38
 *  *****************************************************************************
 */


(function (jQuery) {
    var jQversion = jQuery.fn.jquery.split(".");
	if(jQversion[1]<8)
		return;

	jQuery.browser = {};
	jQuery.browser.mozilla = false;
	jQuery.browser.webkit = false;
	jQuery.browser.opera = false;
	jQuery.browser.msie = false;

	var nAgt = navigator.userAgent;
	jQuery.browser.name  = navigator.appName;
	jQuery.browser.fullVersion  = ''+parseFloat(navigator.appVersion);
	jQuery.browser.majorVersion = parseInt(navigator.appVersion,10);
	var nameOffset,verOffset,ix;

//	In Opera, the true version is after "Opera" or after "Version"
	if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
		jQuery.browser.opera = true;
		jQuery.browser.name = "Opera";
		jQuery.browser.fullVersion = nAgt.substring(verOffset+6);
		if ((verOffset=nAgt.indexOf("Version"))!=-1)
			jQuery.browser.fullVersion = nAgt.substring(verOffset+8);
	}
//	In MSIE, the true version is after "MSIE" in userAgent
	else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
		jQuery.browser.msie = true;
		jQuery.browser.name = "Microsoft Internet Explorer";
		jQuery.browser.fullVersion = nAgt.substring(verOffset+5);
	}
//	In Chrome, the true version is after "Chrome"
	else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
		jQuery.browser.webkit = true;
		jQuery.browser.name = "Chrome";
		jQuery.browser.fullVersion = nAgt.substring(verOffset+7);
	}
//	In Safari, the true version is after "Safari" or after "Version"
	else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
		jQuery.browser.webkit = true;
		jQuery.browser.name = "Safari";
		jQuery.browser.fullVersion = nAgt.substring(verOffset+7);
		if ((verOffset=nAgt.indexOf("Version"))!=-1)
			jQuery.browser.fullVersion = nAgt.substring(verOffset+8);
	}
//	In Firefox, the true version is after "Firefox"
	else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
		jQuery.browser.mozilla = true;
		jQuery.browser.name = "Firefox";
		jQuery.browser.fullVersion = nAgt.substring(verOffset+8);
	}
//	In most other browsers, "name/version" is at the end of userAgent
	else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) <
			(verOffset=nAgt.lastIndexOf('/')) )
	{
		jQuery.browser.name = nAgt.substring(nameOffset,verOffset);
		jQuery.browser.fullVersion = nAgt.substring(verOffset+1);
		if (jQuery.browser.name.toLowerCase()==jQuery.browser.name.toUpperCase()) {
			jQuery.browser.name = navigator.appName;
		}
	}
//	trim the fullVersion string at semicolon/space if present
	if ((ix=jQuery.browser.fullVersion.indexOf(";"))!=-1)
		jQuery.browser.fullVersion=jQuery.browser.fullVersion.substring(0,ix);
	if ((ix=jQuery.browser.fullVersion.indexOf(" "))!=-1)
		jQuery.browser.fullVersion=jQuery.browser.fullVersion.substring(0,ix);

	jQuery.browser.majorVersion = parseInt(''+jQuery.browser.fullVersion,10);
	if (isNaN(jQuery.browser.majorVersion)) {
		jQuery.browser.fullVersion  = ''+parseFloat(navigator.appVersion);
		jQuery.browser.majorVersion = parseInt(navigator.appVersion,10);
	}
	jQuery.browser.version = jQuery.browser.majorVersion;
})(jQuery)

$(document).ready(function(){

	$('#googleCalendarSyncSchedule').hide();
	$('#googleCalendarSyncExams').hide();
	$('#saveSchedule').hide();
	$('#loadSchedule').hide();

	/*variable to hold the current "request" which was earlier*/
	var requestAjax;

	//Global variables (accessed by all screens)
	window.bidit_globals =
	{
			//Globals For google calendar
			g_acsess : false,
			g_url_to_access : '',

			//Current logged in user information
			g_userID: '',
			g_facebookUserID: '',
			g_userEmail: '',
			g_userNickName: '',
			g_loginUrl: '',

			// List of faculties and their departments of the current semester
			g_faculties: [],

            g_helpOptimize: false,
            g_ajaxMiddleShown: true,
            g_ajaxStopMessage: "",
            g_showWelcomePage: true,
            g_userConnected: false,
            g_currHebrewYear: 'תשע"ה',
            g_metaDatesDS: {"metaDates":['10/13/2013','12/01/2013','01/17/2014','02/16/2014','03/16/2014','04/08/2014','04/23/2014','05/05/2014','05/06/2014',
                                            '05/22/2014','06/03/2014','06/04/2014','06/13/2014','10/26/2014','12/21/2014','01/30/2015','03/01/2015',
                                            '03/05/2015','03/30/2015','03/31/2015','04/12/2015','04/22/2015','04/23/2015','05/24/2015','06/19/2015']
                            ,"metaTypes":[['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta']
                                            ,['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],
                                            ['Meta'],['Meta']]
                            ,"metaMoeds":[['meta'],['meta'],['meta'],['meta'],['meta'],['meta'],['meta'],['meta'],['meta'],['meta'],['meta'],['meta'],
                                            ['meta'],['meta'],['meta'],['meta'],['meta'],['meta'],['meta'],['meta'],['meta'],['meta'],['meta'],
                                             ['meta'],['meta']],
                            "metaColors":[['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],
                                            ['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],
                                            ['Meta'],['Meta']]
                            ,"metaNames":[['היום הראשון ללימודים תשע"ד'],['חופשת חנוכה'],['היום האחרון לסמסטר הראשון'],['היום הראשון לסמסטר השני'],
                                        ['פורים'],['היום האחרון ללימודים לפני חופשת פסח'],['היום הראשון ללימודים לאחר חופשת פסח'],
                                        ['יום הזיכרון לחללי מערכות ישראל'],['יום העצמאות'],['יום הסטודנט'],['שבועות'],['שבועות'],
                                        ['היום האחרון לסמסטר ב'],['היום הראשון ללימודים תשע"ה'],['חופשת חנוכה'],['היום האחרון לסמסטר הראשון'],
                                        ['היום הראשון לסמסטר השני'],['פורים'],['יום חלופי לקורסי יום ד'],['ום חלופי לקורסי יום ה- יום אחרון לפני פסח'],
                                        ['היום הראשון ללימודים לאחר חופשת פסח'],['יום הזיכרון לחללי מערכות ישראל'],['יום העצמאות'],['חופשת שבועות'],['היום האחרון לסמסטר ב']]
                            ,"metaCrashes":[false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,
                                            false,false,false,false,false,false,false]},
            g_currSemester: 0,
            g_currCourseProfile : '-1',
            g_currChosenInfoBtnFaculty: 'NOT_CHOSEN',
            g_currChosenFacultyName: '',
            g_currChosenFacultyNum: 'NOT_CHOSEN',
            g_printOnlyCurrSem: false,
            g_printBool: false,

            /*all exams: each element in this array is an array with 9 elements, each place: 0-date(Date) ,1-name("Logic") ,2-color("#ffff95") ,3-number("03682170" ,4-moed("א") ,5-type("בחינה סופית") ,6-semester(0) ,7-exam begin hour("14:00") ,8-exam end hour("---") */
            g_examObj: [],
            g_examObj2: [],

            g_firstExamDate: 'today',
            g_currCourseInfo: [],
            g_currCourseUploaded: false,
            g_toSaveSelection: false,
            g_isProfileOpenedFromMain: true,
            g_newChosenCoursesArr: [], // new courses that were chosen in the course catalog
            g_chosenCoursesArr: [[],[]], // total courses the user chose (presented on main screen accordion)
            g_currSpanSub: '',

            //Saves the users schedule for 3 semesters
            g_schedulesArr: [[],[]],
            g_totalHoursArr: ['0','0'],
            g_totalZchutHoursArr: [0.0,0.0],

            /*variable to hold to last width of the window for print*/
            g_printRes: $('html').width(),

            // Saves all the information for courses accordions (from server)
            g_allSemestersAccordions: [[],[]],

            // Info about courses display on schedule
            g_coursesDisplaySettings: [{},{}],


            g_colorsStock: [],
            g_COLORS_FIRST: ["#26FF56","#26FFE7","#FFFF95","#FF6A4C","#6CAFF2","#E2A9F3"],
            g_COLORS_PERMANENT: ["#FF6FAE","#FA8989","#70A46F","#B88A3E","#B9868E","#DFFF26","#FFC226","#A9A17D","#D363F5"],
            g_COLORS_EXTRA: ["#0489B1","#F78181","#04B404","#D8CEF6","#81DAF5","#CEF6CE","#8A0886","#BDBDBD","#868A08","#F5A9BC",
                             "#2E64FE","#CED8F6","#FF0040","#81F79F","#9F81F7","#CEF6F5","#DF0101","#4FE717","#F79F81","#FBEFEF",
                            "#F7819F","#00FFBF","#D0A9F5","#F2F5A9","#C8E9F6","#BFFF00","#F6229A","#DBA901","#DF01D7","#BE99AE",
                            "#15AC84","#F2A376","#F4F40A","#AC10F4","#1099F4","#10F4F4","#C9DAB2","#F43575","#DBA4F9","#25EB17",
                            "#B64E09","#949EC9","#31D8CA","#F2EB1A","#AF18A5"],
            g_scheduleColors: [],
            g_jsonOptimizer: [],
            g_contactFormBool: {"nameContact":false, "emailContact":false, "subjectContact":false, "freeText":false},
            g_supportToMail: 'bidit.contact@gmail.com',
            g_supportFromMail: 'bidit.contact@gmail.com',
            g_supportFromMailTxt: '',
            g_supportFromName: '',
            g_supportMailBody: '',
            g_supportMailSubject: ''
	};

	/* Initializing login process*/
	getLoginUrl();
	clearOldCookies(); //Initializing cookies every day
	copyColorsArray(); /*Shuffle the permanent colors array, and then adding the extra colors array, finally reversing the order for the algorithm to work*/
	checkForStoredData(); // Checks if there is support for local storage
	checkIfSwitchNeeded(); /*Check if need to switch to semester B*/
	updateExamsAndCalendar(); /*Update exams and calendar*/
	clearAndFocusCourseSearch(); /*Clear and focus on course search*/

    if((jQuery.browser.name.toLowerCase() == 'safari') ||
			(navigator.userAgent.toLowerCase().indexOf('Safari') > -1)){
		$('#fbLikeLIGapped').css('margin-left','132px','!important');
	}

	//The function checks if this is the first time the user entered today to the site, if it is - it deletes the old cookies
	//This happens to ensure the cookies will be up to date with the DB information.
	function clearOldCookies(){
		var currDate = new Date();
		var currDay = currDate.getDay();
		var currMonth = currDate.getMonth();
		var currYear = currDate.getFullYear();

		var strCurrDate = currDay + "-" + currMonth + "-" + currYear;

		if(typeof(Storage)!=="undefined")
		{

			if(localStorage.biditLastUpdate == null){
				//Update cookie to be current date
				localStorage.biditLastUpdate = strCurrDate;

				//Initializing cookies value to be 'none'
				localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
				localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);
				localStorage.setItem('catalog_modal_details_semestera','-100');
				localStorage.setItem('catalog_modal_details_semesterb','-100');

			}
			else{
				if(localStorage.biditLastUpdate == strCurrDate){
					//do nothing
				}
				else{
					//Update cookie to be current date
					localStorage.biditLastUpdate = strCurrDate;

					//Initializing cookies value to be 'none'
					localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
					localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);
					localStorage.setItem('catalog_modal_details_semestera','-100');
					localStorage.setItem('catalog_modal_details_semesterb','-100');
				}
			}
		}
		else
		{
			showAlert('הדפדפן שלך אינו תומך בשימוש באתר זה, עליך לעדכן אותו', 'error');
		}

	}

    //Initializing colors array
    function copyColorsArray(){

        window.bidit_globals.g_colorsStock = [];
        arrayShuffle(window.bidit_globals.g_COLORS_FIRST);
        arrayShuffle(window.bidit_globals.g_COLORS_PERMANENT);
        window.bidit_globals.g_colorsStock = window.bidit_globals.g_colorsStock.concat(window.bidit_globals.g_COLORS_FIRST);
        window.bidit_globals.g_colorsStock = window.bidit_globals.g_colorsStock.concat(window.bidit_globals.g_COLORS_PERMANENT);
        window.bidit_globals.g_colorsStock = window.bidit_globals.g_colorsStock.concat(window.bidit_globals.g_COLORS_EXTRA);
        window.bidit_globals.g_colorsStock.reverse();

    }

	// The function checks of there is a local schedule data saved in the user's computer
	function checkForStoredData(){
		initAutoComplete();
		if(typeof(Storage)!=="undefined")
		{
			if(localStorage.inWebsiteForTheFirstTime == '1'){

				showStoredScheduleData();
			}
			else{
				localStorage.inWebsiteForTheFirstTime = '1';
				localStorage.isDataSaved_A = '1';
				localStorage.isDataSaved_B = '1';
				localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
				localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);
			}
			//initAutoComplete();
		}
		else
		{
			showAlert('הדפדפן שלך אינו תומך בשימוש באתר זה, עליך לעדכן אותו', 'error');
		}

	}

	function checkIfSwitchNeeded(){
		if (localStorage.currSemesterStored == '1') {

			window.setTimeout(function () {
				$('#semesterB').find('> a').click();
			}, 1);

		}

		else{
			getFacFromAjax();
		}
	}

	/*================================================================================================
	 *                                      Miscellaneous 
	 *================================================================================================
	 */

	$('#myCoursesStack').on('mouseenter',function(){
		$('#clearTimeTable').css('opacity','100');
		$('#unChooseCourses').css('opacity','100');
	});

	$('#myCoursesStack').on('mouseleave',function(){
		$('#clearTimeTable').css('opacity','0.7');
		$('#unChooseCourses').css('opacity','0.7');
	});

	$('#clearTimeTableDiv').on('mouseenter',function(){
		$('#clearTimeTableDiv').tooltip('show');
		$('#clearTimeTableDiv').css('cursor','pointer');
		$('#clearTimeTable').css('cursor','pointer');
	});

	$('#clearTimeTableDiv').on('mouseleave',function(){
		$('#clearTimeTableDiv').tooltip('hide');
		$('#clearTimeTableDiv').css('cursor','default');
	});

	$('#clearTimeTableDiv').on('click',function(){
		var currSemester = window.bidit_globals.g_currSemester;

        while(window.bidit_globals.g_chosenCoursesArr[currSemester].length != 0){
			var course_num = (window.bidit_globals.g_chosenCoursesArr[currSemester])[0];
			removeCourseFromMain(course_num);
		}

		//Init total hours
		window.bidit_globals.g_totalHoursArr[currSemester] = '0';
		window.bidit_globals.g_totalZchutHoursArr[currSemester] = 0.0;
		
		//Updating total hours and total points for current semester
		$('#totalHours').text('שעות: ' + window.bidit_globals.g_totalHoursArr[currSemester]);
		$('#totalZchutHours').text('נקודות זכות: ' + window.bidit_globals.g_totalZchutHoursArr[currSemester]);
	});

	$('#clearTimeTableDiv').tooltip({ placement: 'top', animation: 'false', 
		title: 'רוקן את מאגר הקורסים' });

	$('#unChooseCoursesDiv').tooltip({ placement: 'top', animation: 'false', 
		title: 'נקה קורסים שנבחרו' });

	$('#unChooseCoursesDiv').on('mouseenter',function(){
		$('#unChooseCoursesDiv').tooltip('show');
		$('#unChooseCoursesDiv').css('cursor','pointer');
	});

	$('#unChooseCoursesDiv').on('mouseleave',function(){
		$('#unChooseCoursesDiv').tooltip('hide');
		$('#unChooseCoursesDiv').css('cursor','default');
	});

	$('#unChooseCoursesDiv').on('click',function(){
		InitScheduleDisplay();
	});

	$('#yearTab > a').click(function () { return false; });

	$('#yearTab > a').empty();
	$('#yearTab > a').append('מעודכן ל'+window.bidit_globals.g_currHebrewYear);

	$('#facebookLogo').on('mouseover',function(){
		$('#facebookLogo').css("cursor"," pointer");
	});

	$('#facebookLogo').click(function(){
		window.open("https://www.facebook.com/pages/Bid-it/1211188905687121?fref=ts");
	});

    function InitScheduleDisplay(){
        var currSemester = window.bidit_globals.g_currSemester;
        var accordionArr = window.bidit_globals.g_allSemestersAccordions[currSemester];
        window.bidit_globals.g_schedulesArr[currSemester] = [];
        clearTimetableView();

        //Init total hours
        window.bidit_globals.g_totalHoursArr[currSemester] = '0';
        window.bidit_globals.g_totalZchutHoursArr[currSemester] = 0.0;

        //Updating total hours and total zchut hours for current semester
        $('#totalHours').text('שעות: ' + window.bidit_globals.g_totalHoursArr[currSemester]);
        $('#totalZchutHours').text('נקודות זכות: ' + window.bidit_globals.g_totalZchutHoursArr[currSemester]);

        //Init display settings array
        for(var i = 0; i < accordionArr.length; i++){
            var courseNum = accordionArr[i].course_num;
            (window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNum].cChosen = false;
            (window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNum].chosenGroups = 0;

            var courseColor = (window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNum].cColor;
            if(courseColor != 'white'){
                window.bidit_globals.g_scheduleColors.splice(window.bidit_globals.g_scheduleColors.indexOf(courseColor),1);
                window.bidit_globals.g_colorsStock.push(courseColor);
                (window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNum].cColor = 'white';
            }
            var groupsArr = accordionArr[i].group_data;
            for(var j = 0; j < groupsArr.length; j++){
                var groupNum = groupsArr[j].group_num;
                var isGroupChosen = ((window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNum]).groups[groupNum].gChosen;
                if(isGroupChosen){
                    var currGroupElement = $('li[name="'+ courseNum + groupNum +'"]');
                    currGroupElement.removeClass('course-cell-highlight');
                    currGroupElement.addClass('course-cell-hover');
                    ((window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNum]).groups[groupNum].gChosen = false;
                }
                $('#'+courseNum).css({'background-color': 'white'});
            }
        }

        //Update local storage with the latest data
        localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
        localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);

        /*update exams and calendar*/
        updateExamsAndCalendar();

        /*clear and focus on course search*/
        clearAndFocusCourseSearch();
    }

    /*================================================================================================
     *                                       Welcome Page
     *================================================================================================
     */

	$('#neverShowAgain').change(function() {

		if ($("#neverShowAgain").is(':checked')) {
			localStorage.showWelcomePage = 0;
			document.getElementById("neverShowAgain").checked = true;
		}
		else {
			localStorage.showWelcomePage = 1;
			document.getElementById("neverShowAgain").checked = false;
		}

	});

	$('#skipWelcome').click(function() {
		$('#welcomeModal').modal('hide');
	});

    function welcomeWebStorage(){

        /*1-SHOW WELCOME , 0-DONT SHOW*/

        if(typeof(Storage)!=="undefined"){
            if (localStorage.showWelcomePage){
                if (localStorage.showWelcomePage == 1) {
                    document.getElementById("neverShowAgain").checked = false;
                    $('#welcomeModal').modal('show');
                }
                if (localStorage.showWelcomePage == 0) {
                    document.getElementById("neverShowAgain").checked = true;
                }
            }
            else {
                localStorage.showWelcomePage=1;
                welcomeWebStorage();
            }
        }

        /*browser doesnt support*/
        else
        {
            $('#neverShowAgainDiv').empty();
        }
    }

	/*================================================================================================
	 *                                       AUTOCOMPLETE
	 *================================================================================================
	 */

	function initAutoComplete(){
		requestAjax = $.ajax({
			type: "GET",
			url: "/ajax/get-autoComplete-courses/",
			dataType: 'json',
			data: {'semester': '0' + (window.bidit_globals.g_currSemester+1).toString() },

				success: function(data){
					createRelevantAutoComplete(data);
				}
		});//ajax closed
	}

	function createRelevantAutoComplete(data){
        var courses = [];
        var map = {};
		var courseData = data.Courses;

		$.each(courseData, function (i, course) {
			map[course.courseName] = course;
			courses.push(course.courseName);
		});

		$('#search').typeahead({
			source: function (query, process) {
				process(courses);
			}, 

			items: 10, 

			minLength: 1,

			updater: function (item) {
                var selectedCourse;
                if (map[item] == undefined) { /* do nothing if there's no course searched for */
                }
                else {
                    selectedCourse = map[item].courseCode;

                    $('#courseTable').empty();
                    $('#chosenCourses').empty();

                    var tempChosenCourseArr = [];

                    if (window.bidit_globals.g_chosenCoursesArr[window.bidit_globals.g_currSemester].indexOf(selectedCourse) == -1) {
                        tempChosenCourseArr.push(selectedCourse);
                    }

                    /* Ask chosen courses info from server and present it on main screen */
                    chosenCoursesAjaxRequest(tempChosenCourseArr, false);

                    //Data need to be saved
                    if (window.bidit_globals.g_currSemester == 0) {
                        localStorage.isDataSaved_A = '0';

                    }
                    else {
                        localStorage.isDataSaved_B = '0';
                    }

                    return null;
                }
			}
		});
	}

	/*================================================================================================
	 *                                       Course Catalog Screen
	 *================================================================================================
	 */

	function getFacFromAjax(){
        $.ajax({
            type: "GET",
            url: "/ajax/faculties-list/",
            dataType: 'json',
            data: {'semester': '0' + (window.bidit_globals.g_currSemester+1).toString() },
				success: function(data)
				{
					InitFaculties(data);
				}
		});//ajax closed
	}


	/* Creating the faculties accordion, with all the departments below them */
	function InitFaculties(data){
		var facultiesArr = data.faculties;
		window.bidit_globals.g_faculties = data.faculties;

		// Add faculty filter accordion
		$('<div class="accordion"><div id="facultyFilter" width="100%" class="accordion-group">' +
				'<div width="100%" class="accordion-heading">' +
				'<a id="aFacultyFilter" class="accordion-toggle" data-toggle="collapse" data-parent="#filters-accordion" href="#facultiesList">' +
				'<br/>' + 
				'בחר פקולטה' + 
				'</a>' + 
				'</div>' + 
				'<div id="facultiesList" width="100%" class="accordion-body collapse in pre-scrollable" style="overflow-y:auto; max-height:150px;">' +
				'<ul id="facultiesListInner" class="accordion-inner unstyled">' +
				'</ul>' +
				'</div>' +
		'</div></div>').appendTo('#filters-accordion');


		for(var i=0; i < facultiesArr.length; i++){
			$('<li id="' + facultiesArr[i][1] + '" class="depart-cell-hover faculty-filter-li">' + facultiesArr[i][0] +'</li>').appendTo('#facultiesListInner');
		}
	}

//	------------------------------------ courses filters ----------------------------------------------------

    /* The user clicked on a faculty and chose it */
    $('#filters-accordion').delegate('.faculty-filter-li','click',function() {

        var chosenFacultyNum = $(this).attr('id');
        var chosenFacultyName = $(this).text();
    
        if(window.bidit_globals.g_currChosenFacultyNum != chosenFacultyNum){
            facultyChoose(chosenFacultyNum, chosenFacultyName);
            saveCourseCatalogDetails();
        }
    });

	/* Changes the filter button color when its clicked */
	function changeFilterButtonCss(prevFilterNum,newFilterNum){
		var prevFilter = '#' + prevFilterNum;
		var newFilter = '#' + newFilterNum;

		if(prevFilter != '#NOT_CHOSEN'){
			$(prevFilter).removeClass('depart-cell-highlight');
			$(prevFilter).addClass('depart-cell-hover');
			$(prevFilter).css('cursor','pointer');
		}

		$(newFilter).removeClass('depart-cell-hover');
		$(newFilter).addClass('depart-cell-highlight');
		$(newFilter).css('cursor','default');
	}

    function facultyChoose(chosenFacultyNum,chosenFacultyName){

		changeFilterButtonCss(window.bidit_globals.g_currChosenFacultyNum, chosenFacultyNum);

		window.bidit_globals.g_currChosenFacultyName = chosenFacultyName;
		window.bidit_globals.g_currChosenFacultyNum = chosenFacultyNum;

        coursesByFacAjaxRequest();
	}

	function coursesByFacAjaxRequest(){
		requestAjax = $.ajax({
			type: "GET",
			url: "/ajax/courses-list-by-fac/",
			dataType: 'json',
			data: {'semester': '0' + (window.bidit_globals.g_currSemester+1).toString(),
				    'fac_num': window.bidit_globals.g_currChosenFacultyNum },
				success: function(data)
				{
					showCourseList(data.courses);
				}
		});//ajax closed
	}

//	------------------------------------end of courses filters ----------------------------------------------------

	//the user clicked on choose courses
	$('#chooseCoursesDiv').click(function(){
		var tempCatalogData = null;

        if(window.bidit_globals.g_currSemester==0){
			tempCatalogData = localStorage.getItem('catalog_modal_details_semestera');
		}
		else{
			tempCatalogData = localStorage.getItem('catalog_modal_details_semesterb');
		}

        var tempCourseArray;

        if (tempCatalogData == null) {
            $('#chosenCourses').empty();
        }
        else {
            if (tempCatalogData != '-100') {
                tempCatalogData = JSON.parse(tempCatalogData);
                $('#chosenCourses').empty();

                window.bidit_globals.g_newChosenCoursesArr = tempCatalogData['ccoursenums'];

                facultyChoose(tempCatalogData['cfacultynum'], tempCatalogData['cfacultyname']);

                var facultyNum = tempCatalogData['cfacultyname'];
                var facultyName = '';
                if (facultyNum != 'NOT_CHOSEN') {
                    facultyName = tempCatalogData['cfacultyname'];

                    facultyChoose(facultyNum, facultyName);
                    tempCourseArray = window.bidit_globals.g_newChosenCoursesArr;

                    for (var i = 0; i < tempCourseArray.length; i++) {
                        var courseNum = tempCourseArray[i][0];
                        var courseName = tempCourseArray[i][1];

                        $('<div class="row-fluid cl-' + courseNum + '"id="cc' + courseNum + '" data-course_num=' + courseNum + '><div class="span1"><a id="courseRemoveButton"><i  class="course-action-hover icon-remove icon-large"  ></i></a></div><div class="span1"><a id="chosencourseinfoBtn"  href="#courseProfileModal" data-dismiss="modal"><i id="chosencourseinfo" class="course-action-hover icon-info-sign"  ></i></a></div><div class= "span10">' + courseName + '</div></div>').appendTo('.chosenCourses');
                    }
                }
            }
        }
	});

	/* The user clicked X on a course from the chosen courses tab*/
	$('#chosenCourses').delegate('#courseRemoveButton', 'mouseenter', function() {
		$(this).addClass('icon-white');
	});
	
	$('#chosenCourses').delegate('#courseRemoveButton', 'mouseleave', function() {
		$(this).removeClass('icon-white');
	});

	$('#chosenCourses').delegate('#courseRemoveButton', 'click', function() {
        var courseNum =$(this).closest('div.row-fluid').attr('data-course_num');

        $(this).closest('div.row-fluid').remove();

		$('#lc'+courseNum).removeClass('course-cell-disabled');

        window.bidit_globals.g_newChosenCoursesArr.splice(getIndexForNewChosenCoursesArr(courseNum),1);
		
		saveCourseCatalogDetails();
	});	 

	/* The user clicked on a course and chose it or made it unchosen */
	$('#courseTable').delegate('#course', 'click', function() {

		var isDisabled = $(this).closest('div.row-fluid').hasClass('course-cell-disabled');
		if (isDisabled == false){
            var courseNum = $(this).closest('div.row-fluid').attr("data-course_num");

            //Checks if the course already exist... if not will return -1


            // Gets course' element current class

            // Removes the chosen course from the chosen courses list (and global array)
            $('.cl-' + courseNum).remove();
            window.bidit_globals.g_newChosenCoursesArr.splice(getIndexForNewChosenCoursesArr(courseNum),1);
		}
		saveCourseCatalogDetails();
	});

	/* The user touched an info button with the mouse */
	$('#courseTable').delegate('#infoBtn', 'mouseenter', function() {
		onClickInfoBtn(this);
	});

	$('#chosenCourses').delegate('#chosencourseinfoBtn', 'mouseenter', function() {
		$(this).addClass('icon-white');
		onClickInfoBtn(this);

	});
	
	$('#chosenCourses').delegate('#chosencourseinfoBtn','mouseleave',function(){
		$(this).removeClass('icon-white');
	});

    $('#addCourses').click(function(){
        //Need to save data

        if(window.bidit_globals.g_currSemester == 0){
            localStorage.isDataSaved_A = '0';
        }
        else{
            localStorage.isDataSaved_B = '0';
        }

        window.bidit_globals.g_toSaveSelection = true;

        $('#chosenCourses').empty();
        $('.highlightedCourses').addClass('course-cell-disabled');
        $('.highlightedCourses').removeClass('highlightedCourses');

        var tempCourseArrForAjax =  getCourseNumbersFromNewChosenCourses();
        if (tempCourseArrForAjax.length > 0){
            chosenCoursesAjaxRequest(tempCourseArrForAjax);
        }
        window.bidit_globals.g_newChosenCoursesArr = [];
        saveCourseCatalogDetails();
    });

    $('#courseCatalogExit1').click(function(){
    window.bidit_globals.g_toSaveSelection = false;
    $('#courseCatalogModal').modal('hide');
    });

    $('#courseCatalogExit2').click(function(){
        window.bidit_globals.g_toSaveSelection = false;
        $('#chosenCourses').empty();
        window.bidit_globals.g_newChosenCoursesArr=[];
        saveCourseCatalogDetails();
    });

    /* The scrolling of the course catalog modal */
    $('#courseCatalogModal').css('max-height', '90%');

    /* Shows the courses of the chosen department - in the middle part of the window */
    function showCourseList(coursesArr){
        var currSemester = window.bidit_globals.g_currSemester;
        // Delete the previous courses list
        $('#courseTable').empty();

        if(coursesArr.length == 0){
            $('#courseTable').append('<div style="text-align:center; font-weight:bold;">' + '- לא קיימים קורסים עבור הסינון הנוכחי -' + '</div>');
        }

        $.each(coursesArr,function(){

            var courseCellClass ="depart-cell-highlight";
            if ( getIndexForNewChosenCoursesArr(this.course_num) == -1){
                courseCellClass = "depart-cell-hover";
            }

            // Adding the courses names and an info button to the courses list on screen
            if (window.bidit_globals.g_chosenCoursesArr[currSemester].indexOf(this.course_num) != -1){
                courseCellClass = "course-cell-disabled";
            }

            $('#courseTable').append('<div class="row-fluid '+ courseCellClass +'" id="lc' + this.course_num + '" data-course_num="'+this.course_num+'"data-course_name="'+this.course_name+' " data-facultyNum="' + window.bidit_globals.g_currChosenFacultyNum  + '">' +
                '<div id="info" class="span2 clInfo"  style="margin-top:7px;"><a id="infoBtn" class="btn btn-mini btn-primary" href="#courseProfileModal" data-dismiss="modal" style="font-size:small; font-family:Monospace;"><strong>i</strong></a></div>' +
                '<div id="course" class="span10"   style="margin-top:2px; margin-bottom:2px; direction:rtl;">' + this.course_name + '</div>' +
                '</div>');

            if (window.bidit_globals.g_chosenCoursesArr[currSemester].indexOf(this.course_num) != -1){
                $("this").unbind('mouseenter mouseleave');
            }
        });
    }

	function onClickInfoBtn(btn){
		window.bidit_globals.g_currCourseProfile = $(btn).closest('div.row-fluid').attr("data-course_num");
		window.bidit_globals.g_currChosenInfoBtnFaculty = window.bidit_globals.g_currCourseProfile.substring(0,2);
		window.bidit_globals.g_isProfileOpenedFromMain = false;
		courseProfileInit();
		$(btn).unbind('click');
		$(btn).on('click', function(){
            $.when(getCurrentCourseFromAjax()).done(function (a1) {
                unAssignCourseProfileData();
				checkIfCanAssignProfileData(a1);
				
				//open course profile
				$('#courseProfileModal').modal('show');
			});
		});
	}

	/* Gets the information for chosen courses, to be displayed on the main screen */
	function chosenCoursesAjaxRequest(coursesList){
		openBlockUI();
		var counter = 0;
		var currSemester = window.bidit_globals.g_currSemester;

		requestAjax = $.ajax({
			type: "GET",
			url: "/ajax/chosen-courses-info/",
			data: { 'semester': '0' + (window.bidit_globals.g_currSemester+1).toString(),
				'courses_list': coursesList},
				traditional: true,
				dataType: 'json',
				success: function(data){
					$.each(data.coursesInfo, function(){
						if (checkIfInAccordion(this, currSemester) == false){
							window.bidit_globals.g_allSemestersAccordions[currSemester].push(this);
                            counter++;
						}
					});
					//Presents the chosen courses in the accordion on main screen
					addCoursesToMain(counter, currSemester);
					coursesList = [];
				},
				complete: function() {
					closeBlockUI();
				}
		});//ajax closed
	}

	function checkIfInAccordion(course, semesterNum){
		for (var i = 0 ; i < window.bidit_globals.g_allSemestersAccordions[semesterNum].length ; i++){
			if (window.bidit_globals.g_allSemestersAccordions[semesterNum][i].course_num == course.course_num)
                return true;
		}
		return false;
	}

	/*================================================================================================
	 *                                       Course Profile Screen
	 *================================================================================================
	 */

	function courseProfileInit(){
		if(!window.bidit_globals.g_isProfileOpenedFromMain){
			$('#closeBackToCatalog').show();
			$('#closeBackToMain').hide();
			$('#backToCatalog').show();
			$('#backToMain').hide();
		}
		else{
			$('#closeBackToCatalog').hide();
			$('#closeBackToMain').show();
			$('#backToMain').show();
			$('#backToCatalog').hide();
		}

		$('#courseProfileTabs li').each(function(){
			$(this).removeClass('active'); 
		});
		$('#coursProfileTabsContent div').each(function(){
			$(this).removeClass('active'); 
		});

		$('#courseProfileTabs a:first').tab('show');
		$('#coursProfileTabsContent div:first').tab('show');
	}

	/*function showCourseSyllabus(obj){
		$('#tab3x').empty();
		$.each(obj.syllabus,function(){
			$('#tab3x').append('<p style="direction: rtl !important;">'+this.syl+'</p>');
		});
	} */

	function getCurrentCourseFromAjax(){
		abortAllRequests();
		$.ajaxSetup({
			responseFields: {
				"json": "responseJSON"
			}
		});
		/*for not duplicates information about course in profile*/
		abortAllRequests();
		requestAjax = $.ajax({
			type: "GET",
			url: "/ajax/course-profile-info/",
			dataType: 'json', 
			data: {'semester': '0' + (window.bidit_globals.g_currSemester+1).toString(),
				'faculty' : window.bidit_globals.g_currChosenInfoBtnFaculty,
				'course_num': window.bidit_globals.g_currCourseProfile }

		});//ajax closed
		return requestAjax;
	}

	function checkIfCanAssignProfileData(data){
		if (window.bidit_globals.g_currCourseUploaded == false){
			$.each(data.courseInfo,function(){
				window.bidit_globals.g_currCourseProfile = this.course_num;
				assignCourseProfileData(this);
				window.bidit_globals.g_currCourseUploaded = true;
			});
		}
	}

	function assignCourseProfileData(course){
		$('#courseNameId').text(checkIfDef(course.course_name));
		$('#amountHours').text(checkIfDef(course.course_hours));
		$('#amountPoints').text(analyzePoints(checkIfDef(course.course_points)));
		$('#ProfileModalLabel').text(function(){
			return checkIfDef(course.course_name)+ ' (' + checkIfDef(course.course_num) + ')';
		});
		$('#ProfileModalLabelSmall').empty();
		$('#ProfileModalLabelSmall').append(function(){

            var retString;
			if (checkIfDef(course.faculty) != ''){
				retString = checkIfDef(course.faculty) ;
			}
			return retString;
		});

		$('#marzimTeble').append(function() {
			var retString = "";
			var havurut = [];
			var counter = 1;
			var kindBreak = true;
			var currNum = "";

			/*Loop to count number of havurut*/

			for (var i = 0 ; i< course.course_group.length ; i++){

				if (!havurut.contains(course.course_group[i].group_num)){
					havurut.push(course.course_group[i].group_num);
				}
			}

			/*Setting table headings*/
			if (havurut.length > 0){
				retString += ' <thead><tr class="info" align="center">'+
				'<th><strong>סוג</strong></th>'+
				'<th><strong>מספר</strong></th>'+
				'<th><strong></strong></th>'+
				'<th><strong>מרצה</strong></th>'+
				'<th><strong>יום</strong></th>'+
				'<th><strong>שעה</strong></th>'+
				'<th><strong>מיקום</strong></th>'+
				'</tr> </thead><tbody>';
			}

			/*loop over havurut*/	
			havurut.forEach(function(entry){
				kindBreak = true;

				/*in case there is more than one HAVURA*/
				if (havurut.length > 1) {
					retString += "<tr class='warning profileTableHead'><td colspan='8'><strong>אפשרות "+ counter++ +"</strong></td></tr>";				
				}
                //$$FIX!!
				for (var i = 0 ; i< course.course_group.length ; i++){

					if (course.course_group[i].group_num == entry) {

						for(var j=0 ; j< course.course_group[i].group_data.length ; j++){

							/*case of same group*/
							if (course.course_group[i].group_num == currNum) {
								retString += '<tr>' +
								'<td>' + '"' +'</td>'+
								'<td>' + '"' +'</td>'+
								'<td>' + '' +'</td>'+
								'<td>' + '"' + '</td>'+
								'<td>' + checkIfDef(course.course_group[i].group_data[j].sub_group_day)+'</td>'+
								'<td>' + checkIfDef(course.course_group[i].group_data[j].sub_group_time) +'</td>'+
								'<td>' + checkIfDef(course.course_group[i].group_data[j].sub_group_location + " " +
                                    course.course_group[i].group_data[j].sub_group_room) +'</td>'+
								'</tr>';

								if (i < course.course_group.length-1){
									if (course.course_group[i].group_num != course.course_group[i+1].group_num){
										retString += "</tbody><tbody>";	
									}
								}
							}
							/*case of new group*/
							else {	
								currNum = course.course_group[i].group_num;
								retString += '<tbody><tr>' +
								'<td>' + checkIfDef(course.course_group[i].group_data[j].sub_group_type) +'</td>'+
								'<td>' + checkIfDef(course.course_group[i].group_num) +'</td>'+
								'<td > ' + checkIfDef(course.course_group[i].group_data[j].sub_group_lects.lect_name) + '</td>'+
								'<td>' + checkIfDef(course.course_group[i].group_data[j].sub_group_day)+'</td>'+
                                '<td>' + checkIfDef(course.course_group[i].group_data[j].sub_group_time) +'</td>'+
                                '<td>' + checkIfDef(course.course_group[i].group_data[j].sub_group_location + " " +
                                    course.course_group[i].group_data[j].sub_group_room) +'</td>'+
								'</tr>';

								if (i < course.course_group.length-1){
									if (course.course_group[i].group_num == course.course_group[i+1].group_num){
										retString += "</tbody><tbody>";	
									}
								}
							}
						}
					}
				}

			});
			if (retString != "") retString+="</tbody>";
			return retString;
		});

		$('#mivhanimTable').append(function() {
			var retString = "";
			var matalotKinds = [];

            if (course.course_exams.a != null){
                matalotKinds.push(course.course_exams.a)
            }

            if (course.course_exams.b != null){
                matalotKinds.push(course.course_exams.b)
            }

			if (matalotKinds.length != 0) {

				$('#matalotHeading').append('<strong>מבחן סיום</strong>');

				retString += ' <thead><tr class="info" align="center">'+
				'<th><strong>מועד</strong></th><th><strong>תאריך</strong></th>'+
				'<th><strong>שעות</strong></th><th><strong>מיקום</strong></th><th><strong>הערות</strong></th></tr></thead><tbody>';
			}

            retString += "<tr class='warning profileTableHead'><td colspan='4'><strong>בחינה סופית</strong></td></tr><tbody>";

            if (course.course_exams.a != null){
                retString += '<tr>' +
                    '<td>'א</td>'+
                    '<td>' + checkIfDef(course.course_exams.a.date) + '</td>'+
                    '<td>' + checkIfDef(course.course_exams.a.times) + '</td>' +
                    '<td>' + checkIfDef(course.course_exams.a.locations)+  '</td>'+
                    '<td>' + checkIfDef(course.course_exams.a.notes)+  '</td>'+
                    '</tr>' ;
            }

            if (course.course_exams.b != null){
                retString += '<tr>' +
                    '<td>'ב</td>'+
                    '<td>' + checkIfDef(course.course_exams.b.date) + '</td>'+
                    '<td>' + checkIfDef(course.course_exams.b.times) + '</td>' +
                    '<td>' + checkIfDef(course.course_exams.b.locations)+  '</td>'+
                    '<td>' + checkIfDef(course.course_exams.b.notes)+  '</td>'+
                '</tr>' ;
            }
            retString += "</tdoby>";
			return retString;
		});
	}

	function analyzePoints(num){
		if (num == '0' || num <= 0) return '---';
		else return num;

	}

	function checkIfDef(par){
		if (par == undefined) return '---';
		if (isOnlyWhiteSpace(par)) {
			return '---';
		}
		return par;

	}

	function isOnlyWhiteSpace(word){
		var counter = 0;
		for (var i=0 ; i<word.length ; i++){
			if (word[i] == ' ') counter++;	
		}
		if (counter == word.length) return true;
		return false;
	}

	function unAssignCourseProfileData(){
		$("#ProfileModalLabel").text(function(){
			return '';
		});

		$('#ProfileModalLabelSmall').text(function(){
			return '';
		});

		$("#marzimTeble").text(function(){
			return '';
		});
		$("#metargelimTable").text(function(){
			return '';
		});
		$('#matalotHeading').text(function(){
			return '';
		});
		$("#mivhanimTable").text(function(){
			return '';
		});

		$("#amountHours").text(function(){
			return '';
		});

		$("#amountPoints").text(function(){
			return '';
		});

		window.bidit_globals.g_currCourseUploaded=false;

		$('#moreOnSeker').popover('hide');

	}

	Array.prototype.contains = function(obj) {
		var i = this.length;
		while (i--) {
			if (this[i] == obj) {
				return true;
			}
		}
		return false;
	}

//	/*================================================================================================
//	 *                                       Optimize Screen
//	 *================================================================================================
//	 */
//
////	$.xhrPool and $.ajaxSetup are the solution
//	$.xhrPool = [];
//	$.xhrPool.abortAll = function() {
//		$(this).each(function(idx, jqXHR) {
//			jqXHR.abort();
//		});
//		$.xhrPool = [];
//	};
//
//	$.ajaxSetup({
//		beforeSend: function(jqXHR) {
//			$.xhrPool.push(jqXHR);
//		},
//		complete: function(jqXHR) {
//			var index = $.xhrPool.indexOf(jqXHR);
//			if (index > -1) {
//				$.xhrPool.splice(index, 1);
//			}
//		}
//	});
//
//	function abortAllRequests(){
//		requestAjax.abort();
//	}
//
//	function openBlockUI(){
//
//		$.blockUI({ message: $('#wait'), css: {
//			centerX: true,
//			centerY: true,
//			height: '100',
//			width: '100',
//			border: 'none',
//			padding: '15px',
//			left: '48%',
//			backgroundColor: '#000',
//			'-webkit-border-radius': '10px',
//			'-moz-border-radius': '10px',
//			opacity: .8,
//			color: '#fff'
//		}});
//    }
//
//    function closeBlockUI(){
//		$.unblockUI();
//		clearAndFocusCourseSearch();
//	}
//
//	function clearAndFocusCourseSearch(){
//		/*clear and focus on course manual search every time after blockUI*/
//		$("#search").focus();
//		$("#search").val('');
//	}

	/*================================================================================================
	 *                                       Build Time Table Screen (Main Screen)
	 *================================================================================================
	 */

    /* The actual semester switching - the user clicked on a semester tab */
    $('#semesterA').click(function(){
        if(window.bidit_globals.g_currSemester != 0){
            window.bidit_globals.g_currSemester = 0;
            SemestersSwitch();
            $('#CatalogModalLabel').text("בחר קורסים והוסף למערכת (סמסטר א')");
        }
    });

    $('#semesterB').click(function(){
        if(window.bidit_globals.g_currSemester != 1){
            window.bidit_globals.g_currSemester = 1;
            SemestersSwitch();
            $('#CatalogModalLabel').text("בחר קורסים והוסף למערכת (סמסטר ב')");
        }
    });

    /* The user clicked on a course's group */
    $('#accordion2').delegate('.courseGroup', 'click', function() {
        var chosenGroup = $(this);
        var chosenGroupNum =  chosenGroup.attr('title');
        var chosenCourseNum = chosenGroup.attr('id');

        changeCourseDisplayOnAccordion(chosenGroup, chosenCourseNum, chosenGroupNum, true);

        /*refreshing the calendar and exams*/
        updateExamsAndCalendar();

    });


    $(window).resize(function() {
    $("html").width($(window).width());
    clearTimetableView();
    updateTimeTableView();
});

    $('#accordion2').delegate('#mInfoBtn','mouseenter',function(){
        $(this).addClass('icon-white');
        window.bidit_globals.g_currCourseProfile = $(this).closest('div').attr('id');
        window.bidit_globals.g_currChosenInfoBtnFaculty = window.bidit_globals.g_currCourseProfile.substring(0,2);
        window.bidit_globals.g_isProfileOpenedFromMain = true;
        courseProfileInit();

        $(this).on('click', function(){
            $('#tab3x').empty();
            var syllabusRequestAjax = $.ajax({//%%
                type: "GET",
                url: "/ajax/get-syllabus/",
                dataType: 'json',
                data: {'%%semester': (window.bidit_globals.g_currSemester + 1),
                    'course_num': window.bidit_globals.g_currCourseProfile },
                success: function (data) {
                    syllabusRequestAjax = null; //%%
                    showCourseSyllabus(data);
                }
            });//ajax closed

        $.when(getCurrentCourseFromAjax()).done(function (a3) {
        unAssignCourseProfileData();
                checkIfCanAssignProfileData(a3);
                $('#courseProfileModal').modal('show');
            });
        });
    });

    $('#accordion2').delegate('#mInfoBtn','mouseleave',function(){
    $(this).removeClass('icon-white');
});

    $('#accordion2').delegate('#mChosenCourseRemove','mouseenter',function(){
    $(this).addClass('icon-white');
});

    /* The user removed a course from main screen accordion */
    $('#accordion2').delegate('#mChosenCourseRemove','click',function(){
        var course_num = $(this).closest('div').attr('id');

        removeCourseFromMain(course_num);

        //Update local storage with the latest data
        localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
        localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);
    });

    $('#accordion2').delegate('#mChosenCourseRemove','mouseleave',function(){
        $(this).removeClass('icon-white');
    });

    /* The user's mouse is over a course in the main accordion */
    $('#accordion2').delegate('.accordion-group','mouseenter',function(){
        var infoBtnElement = $(this).find('#mInfoBtn');
        var removeBtnElement = $(this).find('#mChosenCourseRemove');

        infoBtnElement.children().css('opacity','100');
        removeBtnElement.children().css('opacity','100');

    });

    $('#accordion2').delegate('.accordion-group','mouseleave',function(){
        var infoBtnElement = $(this).find('#mInfoBtn');
        var removeBtnElement = $(this).find('#mChosenCourseRemove');

        infoBtnElement.children().css('opacity','0.8');
        removeBtnElement.children().css('opacity','0.8');

    });

    /* The user clicked a class on the main screen schedule */
    $('body').delegate('.ttClass','click',function(){
        var courseNum = $(this).attr('id');

        $('#accTog'+courseNum).click();

        showCourseExamClickByCourseNum(courseNum);
    });

	function getDayNum(strDay){
		switch (strDay) {
		case ('א'):
			return 0;
		break;
		case ('ב'):
			return 1;
		break;
		case ('ג'):
			return 2;
		break;
		case ('ד'):
			return 3;
		break;
		case ('ה'):
			return 4;
		break;
		case ('ו'):
			return 5;
		break;
		default:
			return -1;
		}
	}

	// The function empties the main screen and shows the current courses and schedule
	// Uses the SemesterSwitch function and the loadSchedule function 
	function showCurrentCoursesAndSchedule(){
		var currSemester = window.bidit_globals.g_currSemester;
		//Deleting previous semester information from main screen
		$('#accordion2').empty();
		clearTimetableView();		

		//Updating current semester info on main screen 
		var currAccordion = window.bidit_globals.g_allSemestersAccordions[currSemester];
		var displaySettings = window.bidit_globals.g_coursesDisplaySettings[currSemester];
		var MAIN_STR = 'הרצאה';

		// Creating accordion's html tags
		$.each(currAccordion,function(){
            var groupsArr = this.course_group;
			var havuraNum = this.group_num;
            var currCourseNum = this.course_num;
			var courseHeading = this.course_name + ' (' + this.course_num + ')';
			var numOfHavurot = this.group_data.size();
			buildMainCoursesAccordion(currCourseNum,numOfHavurot,courseHeading);

			/* Iterates over the groups of one course */
			$.each(groupsArr,function(){
                var gKind = this.sub_group_type;
				var gNum = this.sub_group_num;
				var gLecturer = this.sub_group_lects.lect_name;

				if(gKind == MAIN_STR){
					addGroupsToMainAccordion(currCourseNum, gNum, gLecturer, havuraNum, 'main');
				}
				else{
					addGroupsToMainAccordion(currCourseNum, gNum, gLecturer, havuraNum, 'sub');
					$('#subBorder' + currCourseNum + havuraNum).show();
				}
			});
		});

		// Updating group selections on main accordion
		$.each(displaySettings, function(){
			var course_num = this.course_num;
			var cColor = this.cColor;
			var courseObj = displaySettings[course_num];
			if(courseObj.cChosen == true){
				//Change chosen course color
				$('#'+course_num).css('background-color',cColor);

				//Iterating over current course's groups
				$.each(courseObj.groups, function(){
					if(this.gChosen == true){
						var currGroupElement = $('li[name="'+ course_num + this.gNum +'"]');
						currGroupElement.removeClass('course-cell-hover');
						currGroupElement.addClass('course-cell-highlight');
					}
				});
			}
		});
        //FIX%%
		// Updating group selections on schedule
		updateTimeTableView();

		//Updating total hours and total zchut hours for current semester
		$('#totalHours').text('שעות: ' + window.bidit_globals.g_totalHoursArr[currSemester]);
		$('#totalZchutHours').text('נקודות זכות: ' + window.bidit_globals.g_totalZchutHoursArr[currSemester]);

		/*refreshing the calendar and exams*/
		updateExamsAndCalendar();

		/*clear and foucs on course search*/
		clearAndFocusCourseSearch();
	}

	function saveCourseCatalogDetails(){
		// save course catalog modal datails for current semester
        var catalog_modal_datails_semester = {'cfacultynum':window.bidit_globals.g_currChosenFacultyNum,'cfacultyname':window.bidit_globals.g_currChosenFacultyName,'ccoursenums':window.bidit_globals.g_newChosenCoursesArr};
		if(window.bidit_globals.g_currSemester == 0){
			localStorage.setItem('catalog_modal_details_semestera',JSON.stringify(catalog_modal_datails_semester));
		}
		else{
			localStorage.setItem('catalog_modal_details_semesterb',JSON.stringify(catalog_modal_datails_semester));
		}

	}

	/* The user switched the schedule to another semester.
	 * This function Updates all screens according to the current semester */
	function SemestersSwitch(){
		initAutoComplete();

		//Changing faculties and departments list on course catalog screen
		$('#filters-accordion').empty();
		$('#filters-accordion-2').empty();
		$('#courseTable').empty();
		$('#dropdownFacultiesList').empty();
		getFacultiesAndDepartsFromAjax();

		//Updates all the courses and schedule on main screen
		showCurrentCoursesAndSchedule();

		//Initializing globals
		window.bidit_globals.g_currCourseProfile = '-1';
		window.bidit_globals.g_currChosenFacultyNum= 'NOT_CHOSEN';
        window.bidit_globals.g_currChosenFacultyName = '';
        window.bidit_globals.g_currChosenInfoBtnFaculty = 'NOT_CHOSEN';
		window.bidit_globals.g_currCourseInfo = [];
		window.bidit_globals.g_currCourseUploaded = false;
		window.bidit_globals.g_toSaveSelection = false;
		window.bidit_globals.g_isProfileOpenedFromMain = true;
		window.bidit_globals.g_jsonOptimizer = [];
		window.bidit_globals.g_newChosenCoursesArr = [];

		/*refreshing the calendar and exams*/
		updateExamsAndCalendar();

		/*clear and foucs on course search*/
		clearAndFocusCourseSearch();

		localStorage.currSemesterStored = window.bidit_globals.g_currSemester;
	}

    /* Checks if all groups of specific havura are chosen */
    function buildMainCoursesAccordion(currCourseNum, numOfHavurot, courseHeading){
        var OPTION_STR = 'אפשרות';
		// each accordion group has 2 ids: "lec-{courseNum}" for lectures list, "rec-{courseNum}" for recitations list
		$('<div id="'+ currCourseNum +'" name="ag' + currCourseNum + '" class="accordion-group">'+
				'<div class="accordion-heading row-fluid">' +
				'<div id="'+ currCourseNum + '" class="span1"><a id="mChosenCourseRemove" data-parent="#accordion2"><i class="course-action-hover icon-remove"></i></a></div>' +
				'<div id="'+ currCourseNum + '" class="span1"><a id="mInfoBtn" data-parent="#accordion2"><i class="course-action-hover icon-info-sign"></i></a></div>' +
				'<div class="span8 offset2"><a class="accordion-toggle" id="accTog'+currCourseNum+'" data-toggle="collapse" data-parent="#accordion2" href="#collapse'+ currCourseNum + '">'+ courseHeading +'</a></div>'+
				'</div>'+
				'<div  id="collapse' + currCourseNum + '" class="accordion-body collapse">'+
				'<div class="accordion-inner" id="inner' + currCourseNum + '">').appendTo('#accordion2');

		// Creates number of options for course ("havurot")
		// Each course option will have the id: lec\rec-{course number)-{havura}
		for (var i = 1; i <= numOfHavurot; i++){
			$('<div><div class="bidit-pre" id="havura-' + currCourseNum + i + '" style="margin-bottom:2px;"><div id="course-option" style="margin:1px;"><b>' + OPTION_STR + ' ' + i + '</b></div>' +
					'<ul class="unstyled" id="main-' + currCourseNum + '-' + i + '" style="margin-bottom:0px;">' +			
					'</ul>'+
					'<div id="subBorder'+ currCourseNum  + i +'" style="margin-top:0px;"><div style="border-bottom: 2px solid #dddddd; margin-top:2px;"></div><div style="margin-top:2px;"></div></div>' + 
					'<ul class="unstyled" id="sub-' + currCourseNum + '-' + i + '" style="margin:0px;">' +
			'</ul></div></div>').appendTo('#inner' + currCourseNum);

			$('#subBorder' + currCourseNum + i).hide();

		}

		$('</div>' +
		'</div></div>').appendTo('#accordion2');
	}

	function addGroupsToMainAccordion(currCourseNum, gNum, gLecturer, gHavura, strMainOrSub){

		$('<li name="'+ currCourseNum + gNum +'" id="' + currCourseNum + '" title="' + gNum + '" class="courseGroup course-cell-hover" unstyled">'+
				  
				'<span>' + gNum + ": " + gLecturer + '</span>' +
				
		'</li>').appendTo('#' + strMainOrSub + '-' + currCourseNum + '-' + gHavura);
	}

	function createCourseObj(isCourseChosen, currCourseNum, courseName, chosenGroupsNum, courseColor, courseZchutHours, groupsObj, moedType, moed, moedHours, dates, locations){
		var funcCourseObj = {};

		funcCourseObj['cChosen'] = isCourseChosen;
		funcCourseObj['course_num'] = currCourseNum;
		funcCourseObj['course_name'] = courseName;
		funcCourseObj['chosenGroups'] = chosenGroupsNum;
		funcCourseObj['cColor'] = courseColor;
		funcCourseObj['cZchutHours'] = courseZchutHours;
		funcCourseObj['groups'] = groupsObj;

		funcCourseObj['types'] = moedType;
		funcCourseObj['moeds'] = moed;
		funcCourseObj['moedHours'] = moedHours;
		funcCourseObj['dates'] = dates;
		funcCourseObj['locations'] = locations;

		return funcCourseObj;
	}

	function createSubGroupObj(subGroupNum, isSubGroupChosen, subGroupHavura, subGroupHoursArr, subGroupDaysArr, subGroupLocationArr, totalSubGroupHours, subGroupType){
		var funcGroupObj = {};
		var MAIN_STR = 'הרצאה';
		var SUB_STR = 'משנית';

		funcGroupObj['subGroupNum'] = subGroupNum;
		funcGroupObj['isSubGroupChosen'] = isSubGroupChosen;
		funcGroupObj['subGroupHavura'] = subGroupHavura;
		funcGroupObj['subGroupHoursArr'] = subGroupHoursArr;
		funcGroupObj['subGroupDaysArr'] = subGroupDaysArr;


		funcGroupObj['subGroupLocationArr'] = subGroupLocationArr;
		funcGroupObj['totalSubGroupHours'] = totalSubGroupHours;

		if(subGroupType == MAIN_STR){
			funcGroupObj['kind'] = 'main';
		}
		else{
			funcGroupObj['kind'] = 'sub';
		}

		return funcGroupObj;
	}

	function addCoursesToMain(len, semesterNum){
		var currSemester = window.bidit_globals.g_currSemester;
        var isGivenCurrSemester = (currSemester == semesterNum);

		var currAccordion = window.bidit_globals.g_allSemestersAccordions[semesterNum]; /*after the new added*/
		var MAIN_STR = 'הרצאה';
		var SUB_STR = 'משנית';

        /* in case this is the first additions of courses */
		if (currAccordion.length - len == 0 && currAccordion.length > 0){
			openFirstAccordion(currAccordion);
		}

		$.each(currAccordion, function(){

			if(window.bidit_globals.g_chosenCoursesArr[semesterNum].indexOf(this.course_num) == -1){

				//Course Data
				var groupsArr = this.course_group;
				var currCourseNum = this.course_num;
				var courseHeading = this.course_name + ' (' + this.course_num + ')';
				var numOfHavurot = this.course_group.size();
				var courseName = this.course_name;
				var coursePoints = this.course_points;

                var moed = [];
                var moedType = [];
                var moedHours = [];
                var dates = [];
                var locations = [];

				//Tests Data
				if (this.course_exams.a != null){
                    moed.push('א');
                    moedType.push('בחינה סופית');
                    moedHours.push(this.course_exams.a.times);
                    dates.push(this.course_exams.a.date);
                    locations.push(this.course_exams.a.locations);
                }

                if (this.course_exams.b != null){
                    moed.push('ב');
                    moedType.push('בחינה סופית');
                    moedHours.push(this.course_exams.b.times);
                    dates.push(this.course_exams.b.date);
                    locations.push(this.course_exams.b.locations);
                }


				// Adding the new chosen courses from the server to the global courses array
				window.bidit_globals.g_chosenCoursesArr[semesterNum].push(currCourseNum);

				// (Display Settings) Initializing and adding new course display object to global display array
				var courseObj = {};
				courseObj = createCourseObj(false, currCourseNum, courseName, 0, 'white', coursePoints, {}, moedType, moed, moedHours, dates, locations);

				if(isGivenCurrSemester){
					buildMainCoursesAccordion(currCourseNum, numOfHavurot, courseHeading);
				}

                $.each(groupsArr, function(){
                    courseObj.groups[group_num] = {};
                });

				/* Iterates over the groups of one course */
				$.each(groupsArr.group_data,function(){
				    var subGroupHavura = groupsArr.group_num;
					var subGroupNum = this.sub_group_num;
					var subGroupLecturer = this.sub_group_lects.lect_name;
					var subGroupType = this.sub_group_type;
					var subGroupDay = this.sub_group_day;
					var subGroupHours = this.sub_group_time;
					var subGroupLocation = this.sub_group_location + ' ' + sub_group_room ;
					var subGroupDuration = this.sub_group_duration;

					// (Display Settings)
					var groupObj = {};

					if(isGivenCurrSemester){
						if(subGroupType == MAIN_STR){
							addGroupsToMainAccordion(currCourseNum, subGroupNum, subGroupLecturer, subGroupHavura, 'main');
						}
						else {
							addGroupsToMainAccordion(currCourseNum, subGroupNum, subGroupLecturer, subGroupHavura, 'sub');

							$('#subBorder' + currCourseNum + subGroupNum).show();
						}	
					}
					groupObj = createSubGroupObj(subGroupNum, false, subGroupHavura, subGroupHours, subGroupDay, subGroupLocation, subGroupDuration, subGroupType);

					// (Display Settings)
					courseObj.groups[subGroupNum.toString()] = groupObj;

				});

				// (Display Settings)
				(window.bidit_globals.g_coursesDisplaySettings[semesterNum])[currCourseNum.toString()] = courseObj;

			}
		});

		//Update local storage with the latest data
		localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
		localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);

	}

    function UpdateTotalHours(currSemester, currGroupObj, op, isCurrentSemester) {
        // Update total hours of courses in schedule
		var tmpHours = parseInt(currGroupObj.gHours.substring(0, currGroupObj.gHours.indexOf(':')));
		var tmpMinutes = parseInt(currGroupObj.gHours.substring(currGroupObj.gHours.indexOf(':')+1,currGroupObj.gHours.length));

		var gTotalHours = window.bidit_globals.g_totalHoursArr[currSemester];
		var currHours = 0;
		var currMinutes = 0;
		if(gTotalHours.indexOf(':') != -1){
			currHours = parseInt(gTotalHours.substring(0, gTotalHours.indexOf(':')));
			currMinutes = parseInt(gTotalHours.substring(gTotalHours.indexOf(':')+1,gTotalHours.length));
		}
		else{
			currHours = gTotalHours;
		}

		var currTotalMinutes = currHours*60 + currMinutes;
		var tmpTotalMinutes = tmpHours*60 + tmpMinutes;
		var minutesToAdd = 0;
		var hoursToAdd = 0;
		if(op == 'add'){			
			minutesToAdd = Math.round((currTotalMinutes + tmpTotalMinutes)%60);
			hoursToAdd = parseInt((currTotalMinutes + tmpTotalMinutes)/60);

		}
		else if(op == 'remove'){
			minutesToAdd = Math.round((currTotalMinutes - tmpTotalMinutes)%60);
			hoursToAdd = parseInt((currTotalMinutes - tmpTotalMinutes)/60);
		}


		if(minutesToAdd == 0){
			window.bidit_globals.g_totalHoursArr[currSemester] =  hoursToAdd.toString();
		}
		else{
			window.bidit_globals.g_totalHoursArr[currSemester] = hoursToAdd + ':' + minutesToAdd;		
		}

		if(isCurrentSemester){
			$('#totalHours').text('שעות: ' + window.bidit_globals.g_totalHoursArr[currSemester]);	
		}
	}

	function UpdatePoints(currSemester,currCourseObj,op,isCurrentSemester){
		if(op == 'add'){
			window.bidit_globals.g_totalZchutHoursArr[currSemester] = window.bidit_globals.g_totalZchutHoursArr[currSemester] + parseFloat(currCourseObj.cZchutHours);
		}
		else if(op == 'remove'){
			window.bidit_globals.g_totalZchutHoursArr[currSemester] = window.bidit_globals.g_totalZchutHoursArr[currSemester] - parseFloat(currCourseObj.cZchutHours);

		}
		
		if(isCurrentSemester){
			$('#totalZchutHours').text('נקודות זכות: ' + window.bidit_globals.g_totalZchutHoursArr[currSemester]);	
		}
	}

	/* The user clicked on a course's group */
    function changeCourseDisplayOnAccordion(courseGroupElem, courseNum, courseGroupNum, isGroupClicked) {
        var currSemester = window.bidit_globals.g_currSemester;
		var courseNumStr = courseNum.toString();
		var groupNumStr = courseGroupNum.toString();
		var currCourseObj = (window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr];
		var currGroupObj = currCourseObj.groups[groupNumStr];

		var hours = currGroupObj.hours;
		var day = currGroupObj.day;
		var place = currGroupObj.place;

        var colorArr = window.bidit_globals.g_colorsStock;
		//Checks if this group has already been chosen, saves a boolean
		var isGroupChosen = currGroupObj.gChosen;

		//Checks if the user already chose a group from this course, saves a boolean
		var isCourseChosen = currCourseObj.cChosen;

        // If group not chosen - Colors the chosen group of the specific course
		if(!isGroupChosen){

			// Update total hours of courses in schedule
			var tmpHours = parseInt(currGroupObj.gHours.substring(0, currGroupObj.gHours.indexOf(':')));
			var tmpMinutes = parseInt(currGroupObj.gHours.substring(currGroupObj.gHours.indexOf(':')+1,currGroupObj.gHours.length));
			if(startHours.length == 0 || endHours.length == 0 || day.length == 0 || (tmpHours == 0 && tmpMinutes == 0)){ //%%
				if(isGroupClicked){
					showAlert('שים לב: לקבוצה שבחרת לא קיימים מפגשים במערכת', 'error')
				}
			}

			// Check if there is another chosen group of the same course and the same kind
			// If there is one, unchoose it

			// change group to 'chosen'
			courseGroupElem.removeClass('course-cell-hover');
			courseGroupElem.addClass('course-cell-highlight');
			(window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr].groups[groupNumStr].gChosen = true;
			((window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr].chosenGroups)++;

			UpdateTotalHours(currSemester,currGroupObj,'add', true);

			// If course not chosen - change the color of the entire course accordion-block
			if(!isCourseChosen){

				//Gets a color from colors array
				currColor = colorArr.pop();
				window.bidit_globals.g_scheduleColors.push(currColor);
				//Updates chosen course color
				$('#'+courseNum).css({'background-color': currColor});						

				//Save course color
				(window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr].cColor = currColor;
				//Change course to chosen on global array
				(window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr].cChosen = true;

				UpdatePoints(currSemester,currCourseObj,'add',true);
			}
			//Add group to be presented on schedule and to the schedule global array
			addGroupToSchedule(currSemester,courseNumStr,groupNumStr,startHours,endHours,day,place);
		}
		// If group is already chosen - uncolors the chosen group of the specific course 
		else{
			courseGroupElem.removeClass('course-cell-highlight');
			courseGroupElem.addClass('course-cell-hover');
			((window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr]).groups[groupNumStr].gChosen = false;
			((window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr].chosenGroups)--;

			// Checks if this group was the only group chosen from its course,saves a boolean
			var isOnlyChosenGroup = (window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr].chosenGroups;

			UpdateTotalHours(currSemester,currGroupObj,'remove', true);

			// If it was the only one chosen - uncolor the entire course accordion block
			if(isOnlyChosenGroup == 0){

				var currColor = (window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr].cColor;

				window.bidit_globals.g_scheduleColors.splice(window.bidit_globals.g_scheduleColors.indexOf(currColor),1);
				window.bidit_globals.g_colorsStock.push(currColor);


				$('#'+courseNumStr).css({'background-color': 'white'});
				(window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr].cColor = 'white';
				(window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr].cChosen = false;

				UpdatePoints(currSemester,currCourseObj,'remove',true);
			}
			removeGroupFromSchedule(courseNumStr,groupNumStr);
		}

		//Update local storage with the latest data
		localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
		localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);
	}

	function clearTimetableView() {
		$(".ttClasses .ttClass").remove();
	}

	function updateTimeTableView(){
		var classesElement = $(".ttClasses");
		var currSemester = window.bidit_globals.g_currSemester;

        //Updates depths (for classes conflicts)
		var classes = sortClassesByTime();
		window.bidit_globals.g_schedulesArr[currSemester] = classes;
        var depths = UpdateClassesDepth();

		// (2) Adding to schedule table on screen
		var dCounter = -1;

        var classesNum = classes.length;

		for(var i = 0; i < classesNum; i++){
			var classObj = classes[i];
			var currCourseObj = (window.bidit_globals.g_coursesDisplaySettings[currSemester])[classObj.course_num];
			var currGroupObj = currCourseObj.groups[classObj.gNum];

			//Creates the class text
			var classTextCourse = classObj.gNum + " - " + classObj.course_name;
			var classTextSub =  " (" + currGroupObj.ofenHoraa + ") " + classObj.place;
			//Creates the class text

			var isSpecialCollision = false;
			if(depths[i] <= -2){
				isSpecialCollision = true;
				depths[i] = depths[i] / (-2);
			}
			//Init depth counter 
			if (dCounter == -1) {
				dCounter = depths[i];
			}
			//Create class element
			var classElement = $('<div>').addClass("ttClass");
			classElement.attr('id',classObj.course_num);
			classElement.attr('title',classTextCourse + classTextSub);


			$("<div>").addClass("ttClassColor").appendTo($(classElement));

			/*addition so we can change style*/
			var nodeCourse = document.createTextNode(classTextCourse);
			var nodeSub = document.createTextNode(classTextSub);
			var spanCourse = document.createElement('span');
			var spanSub = document.createElement('span');
			var linebreak = document.createElement('br');
			spanCourse.style.fontWeight = "bold";
			spanCourse.style.fontSize = "12px";
			spanSub.style.fontWeight = "lighter";
			spanSub.style.direction = "rtl";
			spanSub.style.textAlign = "right";
			spanSub.style.cssFloat = "right";
			//spanSub.className = "";

			spanCourse.appendChild(nodeCourse);
			spanCourse.appendChild(linebreak);
			spanSub.appendChild(nodeSub);

			classElement.append(spanCourse); /*was*/
			classElement.append(spanSub);
			classElement.css('background-color',currCourseObj.cColor);
			classElement.css('overflow','hidden');
			/*end of addition*/


			try{
				//Position and Size
				var startHour = new Date(2000, 1, 1, classObj.startHour.substr(0,2), classObj.startHour.substr(3,2), 0, 0)
				var endHour = new Date(2000, 1, 1, classObj.endHour.substr(0,2), classObj.endHour.substr(3,2), 0, 0)


				//Top
				var rowName = "#row_" + (startHour.getHours() <= 9 ? "0" + startHour.getHours() : startHour.getHours()) + "00";
				var top = $(rowName).position().top + startHour.getMinutes() * $(rowName).height() / 60;

				//Width
				var width = $("#" + getDayNum(classObj.day) + getHour(classObj.startHour) + "00").outerWidth();
				width = width / (depths[i] + 1);

				//Left
				var left = $("#" + getDayNum(classObj.day) + getHour(classObj.startHour) + "00").position().left + width * (depths[i] - dCounter);

				//Height
				rowName = "#row_" + (endHour.getHours() <= 9 ? "0" + endHour.getHours() : endHour.getHours()) + "00";
				var bottom = $(rowName).position().top + endHour.getMinutes() * $(rowName).height() / 60;
				var height = bottom - top;
				top = top + 2;
				left = left + 1;

				$(classElement).css("left", left + "px");
				$(classElement).css("top", top + "px");
				$(classElement).css("height",height + "px");
				$(classElement).css("width", width + "px");

				$(classElement).appendTo($(classesElement));

				if(depths[i+1] >= 0){
					dCounter--;
				}

			}
			catch(e){
				continue;
			}
		}
	}

	function addGroupToSchedule(semester,courseNumStr,groupNumStr,startHoursArr,endHoursArr,day,placesArr){
		//Clear current courses
		clearTimetableView();

		var currSemester = semester;
		var classesNum = day.length; // Number of 'mifgashim' of this course &&
		var courseObj = (window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr];

		// Adds the class object to schedule array and to schedual table on screen
		// (1) Adding to classes Array
		for(var i=0; i < classesNum; i++){
			var classObj = {}
			classObj['course_name'] = courseObj.course_name;
			classObj['course_num'] = courseNumStr;
			classObj['gNum'] = groupNumStr;
			classObj['day'] = day[i];
			classObj['startHour'] = startHoursArr[i];
			classObj['endHour'] = endHoursArr[i];
			classObj['place'] = placesArr[i];

			window.bidit_globals.g_schedulesArr[currSemester].push(classObj);

		}

		updateTimeTableView();

	}

	function findCourseIndexInScheduleArr(course_num,gNum,currSemester){
		var schedArr = window.bidit_globals.g_schedulesArr;

		for(var i = 0; i < schedArr[currSemester].length; i++){
			if(schedArr[currSemester][i].course_num == course_num && schedArr[currSemester][i].gNum == gNum){
				return i;
			}
		}
		return -1;
	}

	/**
	 * removes groups info from the classes array
	 */
	function removeGroupFromScheduleArray(currSemester,courseNumStr,groupNumStr){

		var isAllRemoved = false;
		while(isAllRemoved == false){
			var cIndex = findCourseIndexInScheduleArr(courseNumStr,groupNumStr,currSemester);
			if(cIndex == -1){
				isAllRemoved = true;
			}
			else{
				window.bidit_globals.g_schedulesArr[currSemester].splice(cIndex,1);
			}	
		}		
	}

	function removeGroupFromSchedule(courseNumStr,groupNumStr){
		//Remove from array
		var currSemester = window.bidit_globals.g_currSemester;

		removeGroupFromScheduleArray(currSemester,courseNumStr,groupNumStr);

		//Remove from screen
		//Clear current courses
		clearTimetableView();
		updateTimeTableView();
	}

	function UpdateClassesDepth(){
		var currSemester = window.bidit_globals.g_currSemester;
		var classesArr = window.bidit_globals.g_schedulesArr[currSemester];

		var depths = [];
		var currentDepth = 0;

		depths[0] = 0;

		//analyze depth for each class
		for (var i = 0; i < classesArr.length - 1; i++) {

			var cCurrent = classesArr[i];
			var cNext = classesArr[i+1];
			//var cPrev = 0;


            var currentEndHour = parseInt(cCurrent.endHour);
			var nextStartHour = parseInt(cNext.startHour);

			if (cCurrent.day == cNext.day && currentEndHour > nextStartHour) {
				//update previous
				for (var j = i - currentDepth; j <= i; j++) {
					depths[j] = currentDepth + 1;
				}

				currentDepth++;
				depths[i + 1] = currentDepth;
			}
			else {
				var isCollideWithPrev = false;
				for(var k=0; k < i ; k++){
					var cPrev = classesArr[k];
					var prevEndHour = parseInt(cPrev.endHour);
					if(cPrev.day == cNext.day && prevEndHour > nextStartHour){
						depths[i+1] = depths[k] * -2;
						isCollideWithPrev = true;
					}
				}

				if(!isCollideWithPrev){
					currentDepth = 0;
					depths[i + 1] = 0;
				}
			}
		}
		return(depths);
	}

	function sortClassesByTime(){
		var currSemester = window.bidit_globals.g_currSemester;
		var oldClasses = window.bidit_globals.g_schedulesArr[currSemester];
		var classes = [];

		//order all classes by time
		for (var i = 0; i < oldClasses.length; i++) {
			var c = oldClasses[i];
			var cDay = getDayNum(c.day) + 1;
            var cStartHour = parseInt(getHour(c.startHour).replace(/^0+/, ''));

			var added = false;

			for (var k = 0; k < classes.length; k++) {

				var kDay = getDayNum(classes[k].day) + 1;
                var kStartHour = parseInt(getHour(classes[k].startHour).replace(/^0+/, ''));
				var cVal = cStartHour + cDay * 10000;
				var kVal = kStartHour + kDay * 10000;

				if (kVal > cVal) {
					if (k > 0) {
						classes.splice(k, 0, c);
					}
					else {
						classes.splice(0, 0, c);
					}
					added = true;
					break;
				}
				else if (kVal == cVal) {

					if (k + 1 < classes.length) {
						classes.splice(k + 1, 0, c);
						added = true;
						break;
					}
					else {
						classes.push(c);
						added = true;
						break;
					}
				}
			}
			if (!added) {

				classes.push(c);
			}
		}
		return classes;
	}

	//returns an array of course numbers from g_newChosenCourseArr
	function getCourseNumbersFromNewChosenCourses(){
		var res = [];
		for (var i = 0 ; i < window.bidit_globals.g_newChosenCoursesArr.length ; i++){
			res[i] = window.bidit_globals.g_newChosenCoursesArr[i][0];
		}
		return res;
	}

	//returns the index of the tuple by course number. will return -1 if course number doesn't exist in g_newChosenCourseArr
	function getIndexForNewChosenCoursesArr(courseNumber){
		var res = -1;
		for (var i = 0 ; i < window.bidit_globals.g_newChosenCoursesArr.length ; i++){
			if (window.bidit_globals.g_newChosenCoursesArr[i][0] == courseNumber){
				res = i;
			}
		}
		return res;
	}

	function findCourseIndexInAccordionsArr(currSemester,course_num){
		var accordArr = window.bidit_globals.g_allSemestersAccordions[currSemester];

		for(var i=0; i < accordArr.length; i++){
			if(accordArr[i].course_num == course_num){
				return i;
			}
		}
		return -1;
	}

	/**
	 * Use for removing course details from the relevant data structures:
	 * 1. g_coursesDisplaySettings
	 * 2. g_allSemestersAccordions
	 */
	function removeCourseFromDataStructuresHelper(currSemester, course_num){
		var cAccordIndex = findCourseIndexInAccordionsArr(currSemester, course_num);
		while(cAccordIndex != -1){
			window.bidit_globals.g_allSemestersAccordions[currSemester].splice(cAccordIndex,1);
			cAccordIndex = findCourseIndexInAccordionsArr(currSemester, course_num);
		}

		var courseIndex = window.bidit_globals.g_chosenCoursesArr[currSemester].indexOf(course_num);
		window.bidit_globals.g_chosenCoursesArr[currSemester].splice(courseIndex,1);


		//Deleting the course key from the display settings global array
		try{
			delete ((window.bidit_globals.g_coursesDisplaySettings[currSemester])[course_num]);
		}catch(e){}
	}

    function removeCourseFromMain(course_num) {
        var currSemester = window.bidit_globals.g_currSemester;
		var currCourseObj =  (window.bidit_globals.g_coursesDisplaySettings[currSemester])[course_num];


		$('#lc'+course_num).removeClass('course-cell-disabled');
		$('#lc'+course_num).addClass('%%depart-cell-hover');

		$('div[name="ag' + course_num +'"]').remove();

		$.each(currCourseObj.groups,function(){
			var currGroupObj = this;

			// Update total hours of courses in schedual
			if(currGroupObj.gChosen){
				UpdateTotalHours(currSemester,currGroupObj,'remove', true);
			}

			//Deleting course classes("mifgashim") from schedual arr
			removeGroupFromSchedule(course_num,currGroupObj.gNum);

		});


		if(currCourseObj.cChosen){
			UpdatePoints(currSemester,currCourseObj,'remove',true);
		}

		var courseColor = (window.bidit_globals.g_coursesDisplaySettings[currSemester])[course_num].cColor;
		if(courseColor != 'white'){
			var colorIndex = window.bidit_globals.g_scheduleColors.indexOf(courseColor);
			if(colorIndex != -1){
				window.bidit_globals.g_scheduleColors.splice(colorIndex,1);
				window.bidit_globals.g_colorsStock.push(courseColor);
			}
		}		

		removeCourseFromDataStructuresHelper(currSemester, course_num);

		clearTimetableView();

		updateTimeTableView();
		
		/*refreshing the calendar and exams*/
		updateExamsAndCalendar();
		
		/*clear and foucs on course search*/
		//clearAndFocusCourseSearch();

		//Update local storage with the latest data
		localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
		localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);

		//Need to save data
		if(currSemester == 0){
			localStorage.isDataSaved_A = '0';
		}
		else{
			localStorage.isDataSaved_B = '0';
		}


		//Updating total hours and total zchut hours for current semester
		$('#totalHours').text('שעות: ' + window.bidit_globals.g_totalHoursArr[currSemester]);
		$('#totalZchutHours').text('נקודות זכות: ' + window.bidit_globals.g_totalZchutHoursArr[currSemester]);

		/*if there are courses show the optimizer button*/
		showOrHideOptimizeButton();


	}

	/*external function to shuffle an array for the colors to be random*/
	function arrayShuffle(theArray) {
		var len = theArray.length;
		var i = len;
		while (i--) {
			var p = parseInt(Math.random()*len);
			var t = theArray[i];
			theArray[i] = theArray[p];
			theArray[p] = t;
		}
    }

    function openFirstAccordion(currAccordion){

        var firstNum = currAccordion[0].course_num;
		window.setTimeout(function () {
			$('#accTog'+firstNum).click();
		}, 1000);
	}

	/*================================================================================================
	 *                                       Contact
	 *================================================================================================	
	 */

	var validator = $('#contact-form').validate({
				rules: {
					name: {
						minlength: 2,
						required: true
					},
					email: {
						//minlength: 2,
						required: true,
						email: true
					},
					subject: {
						minlength: 2,
						required: true
					},
					message: {
						minlength: 2,
						required: true
					}
				},
				highlight: function(element) {




					$(element).closest('.control-group').removeClass('success').addClass('error');

					var thing = $(element).closest('div').attr('id');
					var valSign = getCorrectValidSignArea(thing);
					$('#'+valSign).empty();
					window.bidit_globals.g_contactFormBool[thing]=false;

				},
				success: function(element) {
					var thing = element.closest('div').attr('id');
					var valSign = getCorrectValidSignArea(thing);

					window.bidit_globals.g_contactFormBool[thing]=true;

					$('#'+valSign).empty();
					$('#'+valSign).append('<img src="assets/img/valid.png" valign="top"/>');

					element
					.addClass('valid')
					.closest('.control-group').removeClass('error').addClass('success');
				}
			});

	function getCorrectValidSignArea(iden){
		switch (iden){
		case 'nameContact':    return 'nameContactValidSignArea';
		break;
		case 'emailContact':    return 'emailContactValidSignArea';
		break;
		case 'subjectContact':    return 'subjectValidSignArea';
		break;
		case 'freeText':    return 'freeTextValidSignArea';
		break;
		}
	}

	/*karin: sending mail on click. need to add to code above initialization to globals, after validating*/
	$('#submitSupportMail').click(function(){
		var contactBool = window.bidit_globals.g_contactFormBool;
		var isMSIE = false;
		if ((jQuery.browser.name.toLowerCase() == 'microsoft internet explorer') ||
				(navigator.userAgent.toLowerCase().indexOf('msie') > -1)){
			isMSIE = true;	
		}

		if (isMSIE == true){
			var sName = document.getElementById("name").value;
			var sMail = document.getElementById("email").value;
			var sSubject = document.getElementById("subject").value;
			var sBody = document.getElementById("message").value;

			if (sName == '') {
				window.bidit_globals.g_supportFromName = 'שם לא ידוע';
			}
			else {
				window.bidit_globals.g_supportFromName = sName;
			}
			if (sMail == '') {
				window.bidit_globals.g_supportFromMailTxt = 'מייל לא ידוע'; 
			}
			else {
				window.bidit_globals.g_supportFromMailTxt = sMail;
			}
			if (sSubject == '') {
				window.bidit_globals.g_supportMailSubject = 'נושא לא ידוע'; 
			}
			else {
				window.bidit_globals.g_supportMailSubject = sSubject;
			}
			if (sBody == '') {
				window.bidit_globals.g_supportMailBody = 'תוכן לא ידוע'; 
			}
			else {
				window.bidit_globals.g_supportMailBody = sBody;
			}
			sendSupportMail();
			$("body").animate({ scrollTop: 0}, 'fast'); 
		}
		else if ((contactBool['nameContact'] && 
				contactBool['emailContact'] &&
				contactBool['subjectContact'] &&
				contactBool['freeText']))
		{
			window.bidit_globals.g_supportFromName = document.getElementById("name").value;
			window.bidit_globals.g_supportFromMailTxt = document.getElementById("email").value;
			window.bidit_globals.g_supportMailSubject = document.getElementById("subject").value;
			window.bidit_globals.g_supportMailBody = document.getElementById("message").value;

			sendSupportMail();
			$("body").animate({ scrollTop: 0}, 'fast'); 
		}
		/*there are still missing areas*/
		else {
			showUnsentMessage();
			//validator;	
		}
	});

	function sendSupportMail(){
		requestAjaxMail = $.ajax({
			type: "GET",
			url: "/ajax/submitMail/",
			dataType: 'json',
			data: { 'toMail': window.bidit_globals.g_supportToMail,
				'fromMail': window.bidit_globals.g_supportFromMail,
				'fromMailTxt': window.bidit_globals.g_supportFromMailTxt,
				'fromName': window.bidit_globals.g_supportFromName,
				'body': window.bidit_globals.g_supportMailBody,
				'subject': window.bidit_globals.g_supportMailSubject},

                success: function () {
                    window.bidit_globals.g_supportFromName = '';
					window.bidit_globals.g_supportFromMailTxt = '';
					window.bidit_globals.g_supportMailSubject = '';
					window.bidit_globals.g_supportMailBody = '';
					resetContact();
					showSentMessege();

				}
		});//ajax closed
	}

	$('#resetContactFormButton').click(function(){
		resetContact();
	});

	function resetContact(){
		var contactBool = window.bidit_globals.g_contactFormBool;

		contactBool['nameContact'] = false; 
		contactBool['emailContact'] = false;
		contactBool['subjectContact'] = false;
		contactBool['freeText'] = false;

		$('#nameContactValidSignArea').empty();
		$('#emailContactValidSignArea').empty();
		$('#subjectValidSignArea').empty();
		$('#freeTextValidSignArea').empty();

		$('#name').val('');
		$('#email').val('');
		$('#subject').val('');
		$('#message').val('');


		$('#nameContact').removeClass('valid error success');
		$('#emailContact').removeClass('valid error success');
		$('#subjectContact').removeClass('valid error success');
		$('#freeTextContact').removeClass('valid error success');

		$('.control-group').removeClass('valid error success');

		hideSentOrUnsentMessege();	
		validator.resetForm();

		$('#contactExit2').removeClass('hide');
		$('#submitSupportMail').removeClass('hide');
		$('#backToMainScreenFromContact').addClass('hide');

	}

	function hideSentOrUnsentMessege(){
		$('#messegeSentArea').empty();
	}

    function showSentMessege(){
		$('#messegeSentArea').empty();
		var mPriority = 'warning';
		var messageToShow = 'נשלח בהצלחה';
		showAlert(messageToShow,mPriority);


		$('#contactModal').modal('hide');	
		$('#contactExit2').addClass('hide');
		/*$('#submitSupportMail').addClass('hide');*/
		$('#backToMainScreenFromContact').removeClass('hide');


	}

	$('#backToMainScreenFromContact').click(function(){
		resetContact();
		$('#contactModal').modal('hide');	

	});

	function showUnsentMessage(){

		$('#messegeSentArea').empty();
		$('#messegeSentArea').append(
				'<h5 style="color: red;"><strong>.אנא מלא את כל הפרטים</strong></h5>'
		);

	}

	$('#contactModal').on('hidden', function (){
		resetContact();

	});

    function showAlert(messageToShow,messagePriority){
		$(document).trigger("add-alerts", [
		                                   {
		                                	   'message': '<div style="color:black;"><strong>'+ messageToShow +'</strong></div>',
		                                	   'priority': messagePriority
		                                   }
		                                   ]);


	}

	$('#contactViaAbout').click(function(){

		$('#aboutModal').modal('hide');	
		$('#contactBtnMain').click();
	});

	/*================================================================================================
	 *                                       Calendar
	 *================================================================================================
	 */

//	$('#txtDate').datepicker({isRTL: true,numberOfMonths: 2 ,yearRange: "-50:+50",
//		monthNames: ['ינואר','פברואר','מרץ','אפריל','מאי','יוני',
//		             'יולי','אוגוסט','ספטמבר','אוקטובר','נובמבר','דצמבר'],
//		             monthNamesShort: ['1','2','3','4','5','6',
//		                               '7','8','9','10','11','12'],
//		                               dayNames: ['ראשון','שני','שלישי','רביעי','חמישי','שישי','שבת'],
//		                               dayNamesShort: ['א\'','ב\'','ג\'','ד\'','ה\'','ו\'','שבת'],
//		                               dayNamesMin: ['א\'','ב\'','ג\'','ד\'','ה\'','ו\'','שבת'],
//		                               dateFormat: 'dd/mm/yyyy',
//		                               firstDay: 0,
//		                               prevText: 'הקודם',  nextText: 'הבא' ,
//		                               defaultDate: window.bidit_globals.g_firstExamDate,
//		                               /*for some reason this doesnt work*/
//		                               //dateFormat: 'dd/mm/yyyy',
//
//		                               /*happens in every refresh of calendar like month change or reload*/
//		                               beforeShowDay: highlightExams
//	});
//
//    $('#examsListBody').delegate('tr','click',function() {
//        showCourseExamClickByDate(this.id);
//    });
//
//	function highlightExams(date) {
//		/*these 3 arrays are coardinated with each other by indexes*/
//
//		var dates = []; //array of dates
//		var types = []; // array of arrays of types
//		var moeds = []; // array of arrays of moeds
//		var colors = []; // array of arrays of colors
//		var names = []; // array of arrays of names
//		var crashes = []; //array of binary identifier
//		$('#ExclamationDiv').empty();
//		return [true, colorExam(date,types,dates,moeds,colors,names,crashes),labelExams(date,types,dates,moeds, names,crashes)];
//		if (crashes.indexOf(true) == -1) {
//			$('#ExclamationDiv').addClass('hide');
//		}
//	}
//
//	function addMetaExamsToArrays(types,dates,moeds,colors,names,crashes){
//		for (var i=0 ; i < window.bidit_globals.g_metaDatesDS["metaDates"].length ; i++){
//			dates.push(window.bidit_globals.g_metaDatesDS["metaDates"][i]);
//			types.push(window.bidit_globals.g_metaDatesDS["metaTypes"][i]);
//			moeds.push(window.bidit_globals.g_metaDatesDS["metaMoeds"][i]);
//			colors.push(window.bidit_globals.g_metaDatesDS["metaColors"][i]);
//			names.push(window.bidit_globals.g_metaDatesDS["metaNames"][i]);
//			crashes.push(window.bidit_globals.g_metaDatesDS["metaCrashes"][i]);
//		}
//
//	}
//
//	function colorExam(date,types,dates,moeds,colors,names,crashes){
//
//		/*semester A*/
//		runOverSemester(0,date,types,dates,moeds,colors,names,crashes);
//		/*semester B*/
//		runOverSemester(1,date,types,dates,moeds,colors,names,crashes);
//
//		/*adding the meta exams*/
//		addMetaExamsToArrays(types,dates,moeds,colors,names,crashes);
//
//		/*looping over the current chosen courses and colors the correct date*/
//		for (var i = 0; i < dates.length; i++){
//			var tmpDate = dates[i];
//            var tmpCol = colors[i]; //array
//			var tmpCrash = crashes[i];
//			if (tmpCrash==true){
//				showExclamationMark();
//			}
//
//			if (date.getTime() == (new Date(tmpDate).getTime())) {
//				if (tmpCrash==true){
//					/*in case like this need to monitor the user*/
//
//					return 'colorDate'+'Overlap';
//				}
//				else if (tmpCrash==false){
//					if (tmpCol[0] == 'Meta'){
//						return 'colorDateMeta';
//					}
//					return 'colorDate'+tmpCol[0].substring(1,tmpCol[0].length);
//				}
//			}
//        }
//    }
//
//    function runOverSemester(semester, types, dates, moeds, colors, names, crashes) {
//        $.each(window.bidit_globals.g_coursesDisplaySettings[semester],(function(){
//			/*getting date*/
//			/*in case the course is chosen*/
//			if (this.cChosen == true){
//
//				for (var i=0 ; i<this.dates.length ; i++){
//
//                    var dateString ;
//					var d = getDayFromString(this.dates[i]);
//					var m = getMonthFromString(this.dates[i]);
//					var y = getYearFromString(this.dates[i]);
//					if (m.length==1) m="0"+m;
//					dateString = m+"/"+d+"/"+y;
//					/*case of date already exist, and legal date*/
//					if ((dates.indexOf(dateString)) > -1 && (dateString != "//---")){
//
//						//no need to enter date
//						var dateStringIndex = dates.indexOf(dateString);
//						var pushedType = types[dateStringIndex];
//						var pushedMoed = moeds[dateStringIndex];
//						var pushedColor = colors[dateStringIndex];
//						var pushedName = names[dateStringIndex];
//
//						/*getting type*/
//						pushedType[pushedType.length] = this.types[i];
//						types[dateStringIndex]/*[0]*/ = pushedType;
//						/*getting moed*/
//						pushedMoed[pushedMoed.length] = this.moeds[i];
//						moeds[dateStringIndex]/*[0]*/ = pushedMoed;
//						/*getting color*/
//						pushedColor[pushedColor.length] = this.cColor;
//						colors[dateStringIndex]/*[0]*/ = pushedColor;
//						/*getting name of the course*/
//						pushedName[pushedName.length] = this.course_name;
//						names[dateStringIndex]/*[0]*/ = pushedName;
//						/*crash*/
//						crashes[dateStringIndex]=true;
//
//						continue;
//
//					}
//
//					/*case of new date, and legal date*/
//					if (dates.indexOf(dateString)== -1 && (dateString != "//---")) {
//                        dates.push(dateString);
//						/*getting type*/
//						types.push([this.types[i]]);
//						/*getting moed*/
//						moeds.push([this.moeds[i]]);
//						/*getting color*/
//						colors.push([this.cColor]);
//						/*getting name of the course*/
//						names.push([this.course_name]);
//						/*no crash*/
//						crashes.push(false);
//						continue;
//					}
//                }
//            }
//        }));
//	}
//
//    function labelExams(date, types, dates, moeds, names, crashes) {
//        /*looping over the current chosen courses and label the correct text*/
//		for (var i = 0; i < dates.length; i++){
//			var tmpDate = dates[i]; //date
//			var tmpMoedArr = moeds[i]; //array of moeds
//            var tmpNameArr = names[i]; //array of names
//			var tmpTypeArr = types[i]; //array of types
//			var tmpCrash = crashes[i]; //crash
//			if (date.getTime() == (new Date(tmpDate).getTime())) {
//                return printLabels(tmpNameArr, tmpTypeArr, tmpMoedArr, tmpCrash);
//            }
//		}
//
//
//    }
//
//    function printLabels(tmpNameArr, tmpTypeArr, tmpMoedArr, tmpCrash) {
//        if (tmpCrash == false){
//			if (tmpTypeArr[0] == 'Meta'){
//				return tmpNameArr[0];
//			}
//			return tmpNameArr[0]+": "+tmpTypeArr[0]+", מועד "+tmpMoedArr[0]+"'";
//		}
//		if (tmpCrash == true){
//			var retString = '***חפיפה***\n';
//
//			for (var j=0; j<tmpTypeArr.length; j++){
//				retString +=
//					tmpNameArr[j]+": "+tmpTypeArr[j]+", מועד "+tmpMoedArr[0]+"'"+'\n';
//
//			}
//
//			return retString;
//		}
//	}
//
//	function showExclamationMark(){
//		$('#ExclamationDiv').empty();
//		$('#ExclamationDiv').append('<h4 style="color:red;" >*** קיימת חפיפה בין מועדי מבחנים ***</h4>');
//	}
//
//	function getDayFromString(str){
//		var index=0;
//		for(var i=0;i<str.length;i++){
//			if (str[i]=='/')	{
//				index=i;
//				break;
//			}
//		}
//		return str.substring(0,index);
//	}
//
//	function getMonthFromString(str){
//		var index1=0;
//		var index2=0;
//		var thisTime = false;
//		for(var i=0;i<str.length;i++){
//			if (str[i]=='/'){
//				index1=i+1;
//				thisTime=true;
//				continue;
//			}
//
//			if (str[i]=='/' && thisTime)	{
//				index2=i;
//				break;
//			}
//		}
//		return str.substring(str.indexOf('/')+1,str.indexOf('/',str.indexOf('/')+1));
//	}
//
//	function getYearFromString(str){
//		var index1=0;
//		var index2=0;
//		var thisTime = false;
//		for (var i=0;i<str.length;i++){
//			if (str[i]=='/'){
//				index1=i+1;
//				thisTime=true;
//				continue;
//			}
//			if (str[i]=='/' && thisTime)	{
//				index2=i;
//				break;
//			}
//		}
//		return str.substring(str.indexOf('/',str.indexOf('/')+1)+1,str.length);
//	}
//
//	/*should be called every time there is supposed to be change on exams, including when the page loads*/
//	function updateExamsAndCalendar(){
//
//		$('#examsListBody').empty();
//
//		$('#examsListBody').append(function(){
//			var retString = "";
//            /*array which is the first element is dates, second is course name and the third is the color*/
//			window.bidit_globals.g_examObj = [];
//			var obj = window.bidit_globals.g_examObj;
//
//			if (window.bidit_globals.g_printOnlyCurrSem == true){
//				takeParamsToExamsListBody(window.bidit_globals.g_currSemester,obj);
//			}
//			else {
//				/*semester A*/
//				takeParamsToExamsListBody(0,obj);
//
//				/*semester B*/
//				takeParamsToExamsListBody(1,obj);
//			}
//
//
//			/*sort the dates list and assign each color and name*/
//
//
//
//			obj.sort(function(a, b) {
//				var aDate = a[0];
//				var bDate = b[0];
//				return (aDate == bDate) ? 0 : ((aDate > bDate) ? 1 : -1);
//			});
//
//			/*in case of empty exams list the current date is today*/
//			if (obj.length==0) {
//				window.bidit_globals.g_firstExamDate = 'today';
//
//			}
//			/*else the current date the first exam date*/
//			else {
//				window.bidit_globals.g_firstExamDate = obj[0][0];
//			}
//
//			$('#txtDate').datepicker("setDate", window.bidit_globals.g_firstExamDate);
//
//			for (var i=0 ; i<obj.length ; i++){
//				var moedString = '';
//
//				if (obj[i][5] == "בחינה סופית") {
//					moedString = obj[i][1] + ', מועד ' + obj[i][4] + "'";
//				}
//				else {
//					moedString =  obj[i][1] + ', מועד ' + obj[i][4] + "'"+
//					' ('+ obj[i][5] + ')';
//				}
//
//				/*in case there is crash, the next line should be red*/
//				if (crashDate(  printDate(obj[i][0]) ,  obj)) {
//					retString += '<tr style="direction:rtl; cursor: pointer; color: red; font-weight: bold;" id="'+obj[i][0]+'">'+
//					'<td>' +
//					moedString +
//					'</td>'+
//					'<td>' +
//					printDate(obj[i][0]) +
//					'</td>' +
//					'<td>'+
//					'<span style="color: ; " class="bulletSym"  '+obj[i][2]+'">&#9679</span>'+
//					'</td>'+
//					'</tr>';
//				}
//
//				else {
//					retString += '<tr style="direction:rtl; cursor: pointer;"'
//						+' id="'+obj[i][0]+'"><td>' +
//
//						moedString +
//						'</td>'+
//						'<td>' +
//						printDate(obj[i][0]) +
//						'</td>' +
//						'<td>'+
//						'<span style="color: ; " class="bulletSym"  '+obj[i][2]+'">&#9679</span>'+
//						'</td>'+
//						'</tr>';
//				}
//
//
//			}
//
//			//for each exam in increasing order
//
//
//			if (retString == "") {
//				retString += '<tr><td colspan="2">'+'-לוח המבחנים ריק-'+'</td></tr>';
//			}{
//				$('#txtDate').datepicker("refresh" );
//				return retString;
//			}
//		});
//
//		$('#txtDate').datepicker("refresh" );
//
//	}
//
//	/*only for showing bold text*/
//    function crashDate(strDate, obj) {
//        var times = 0;
//		for (var i=0 ; i<obj.length ; i++){
//			if (printDate(obj[i][0]) == (strDate) ) {
//				times++;
//			}
//		}
//		if (times > 1) return true;
//		return false;
//
//	}
//
//	function takeParamsToExamsListBody(semester,obj){
//		$.each(window.bidit_globals.g_coursesDisplaySettings[semester],(function(){
//			/*in case the course is chosen*/
//			if (this.cChosen == true){
//                 //%%FIX
//				for (var i=0 ; i<this.dates.length ; i++){
//                    var dateString ;
//					var d = getDayFromString(this.dates[i]);
//					var m = getMonthFromString(this.dates[i]);
//					var y = getYearFromString(this.dates[i]);
//					if (m.length==1) m="0"+m;
//					dateString = m+"/"+d+"/"+y;
//					var tmpObj = [];
//
//					if (new Date(dateString).toDateString() == "Invalid Date") continue;
//
//					/*getting date*/
//					tmpObj[0]=(new Date(dateString));
//
//					/*getting name of the course*/
//					tmpObj[1]=(this.course_name);
//
//					/*getting color*/
//					tmpObj[2]=(this.cColor);
//
//					/*getting number*/
//					tmpObj[3]=(this.course_num);
//
//					/*getting moed*/
//					tmpObj[4]=(this.moeds[i]);
//
//					/*getting type*/
//					tmpObj[5]=(this.types[i]);
//
//					/*getting semester*/
//					tmpObj[6]=(semester);
//
//					/*getting exam begin hour*/
//					tmpObj[7]=(this['startMoedHours'][i]);
//
//					/*getting exam end hour*/
//					tmpObj[8]=(this['endMoedHours'][i]);
//
//					obj.push(tmpObj);
//
//                }
//            }
//				}));
//	}
//
//	function printDate(date){
//		var d = date.getDate();
//		var m = date.getMonth()+1;
//		var y = date.getFullYear();
//
//		return d+"/"+m+"/"+(y+'').substring(2, 4);
//	}
//
//	function makeDateFromString(str){
//
//		var d = str.substring(0,2);
//		var m = str.substring(3,5);
//		var y= str.substring(6,10);
//		var dateFormat = m+"/"+d+"/"+y;
//		return new Date(dateFormat);
//
//	}
//
//	function showCourseExamClickByCourseNum(courseNum){
//
//		var curSem = window.bidit_globals.g_currSemester;
//		$.each(window.bidit_globals.g_coursesDisplaySettings[curSem],(function(){
//
//			if (this.course_num == courseNum) {
//
//				if ((this.dates[0] != '---')&&(this.dates[0] != undefined)) {
//					var dateToShowFirst = makeDateFromString(this.dates[0]);
//					$('#txtDate').datepicker("setDate", dateToShowFirst);
//				}
//			}
//		}));
//
//		$('#txtDate').datepicker("refresh" );
//	}
//
//	function showCourseExamClickByDate(date){
//		var newDate = new Date(date);
//		$('#txtDate').datepicker("setDate", newDate);
//		$('#txtDate').datepicker("refresh" );
//	}

    /*================================================================================================
	 *                                        User Log-In
	 *================================================================================================
	 */

//	function getLoginUrl(){
//		requestAjax = $.ajax({
//			type: "GET",
//			url: "/login/",
//			dataType: 'json',
//			data: { },
//			success: function(data){
//				//The user is currently not logged in
//				if(data.userLoginStr.urlKind == 'login')
//				{
//					$('#SignInOrOutText').text(' התחבר ');
//					$('#userName').text('');
//					$('#saveSchedule').hide();
//					$('#loadSchedule').hide();
//					//sync with google calendar buttons
//					$('#googleCalendarSyncSchedule').hide();
//					$('#googleCalendarSyncExams').hide();
//					/*due to the extra buttons needed*/
//					clearTimetableView();
//					updateTimeTableView();
//
//					/*showing or not the welcome page*/
//					welcomeWebStorage();
//				}
//				else{
//					$('#SignInOrOutText').text(' התנתק ');
//					$('#userName').text(data.userLoginStr.nickname);
//					$('#saveSchedule').show();
//					$('#loadSchedule').show();
//
//					//Sync with google calendar buttons
//					$('#googleCalendarSyncSchedule').show();
//					$('#googleCalendarSyncExams').show();
//					/*due to the extra buttons needed*/
//					clearTimetableView();
//					updateTimeTableView();
//
//					window.bidit_globals.g_userID = data.userLoginStr.userId;
//					window.bidit_globals.g_userEmail = data.userLoginStr.email;
//					window.bidit_globals.g_userNickName = data.userLoginStr.nickname;
//
//					//check if before logging the user was in the facebook tab
//					var toOpenCourseProfileFacebook = localStorage.courseProfileFacebook;
//					if(toOpenCourseProfileFacebook == null){
//						/*Showing or not the welcome page*/
//						welcomeWebStorage();
//					}
//					else{
//						if(toOpenCourseProfileFacebook == ''){
//							/*Showing or not the welcome page*/
//							welcomeWebStorage();
//						}
//						else{
//							window.bidit_globals.g_currCourseProfile = toOpenCourseProfileFacebook;
//							window.bidit_globals.g_currChosenInfoBtnFaculty = window.bidit_globals.g_currCourseProfile.substring(0,2);
//							window.bidit_globals.g_isProfileOpenedFromMain = true;
//							courseProfileInit();
//							localStorage.courseProfileFacebook = '';
//
//                            $.when(getCurrentCourseFromAjax()).done(function (a3) {
//                                unAssignCourseProfileData();
//								checkIfCanAssignProfileData(a3);
//								$('#courseProfileModal').modal('show');
//
//								//Initializing the facebook tab
//								$('#courseProfileTabs a:eq(5)').tab('show');
//								$('#coursProfileTabsContent div:eq(5)').tab('show');
//								var hasClassDis = $('#popularityTab').hasClass('facebookTabBtnDisabled');
//								if(hasClassDis == false){
//									$('#popularityTab').addClass('facebookTabBtnDisabled');
//									updatePopularityTab(true);
//								}
//							});
//						}
//					}
//				}
//				window.bidit_globals.g_loginUrl = data.userLoginStr.currUrl;
//				$('#signInButtonMainScreen').attr('name',data.userLoginStr.urlKind);
//
//				requestAjaxSync1 = $.ajax({
//					type: "GET",
//					url: "/",
//					data: { },
//					success: function(data){
//						var linkAttr = $('#SyncAllExams').attr('name');
//
//						if(linkAttr == 'yes'){
//							window.bidit_globals.g_acsess = true;
//							window.bidit_globals.g_url_to_access = '';
//						}
//						else{
//							window.bidit_globals.g_acsess = false;
//							window.bidit_globals.g_url_to_access = data;
//						}
//
//						//if the user asked for sync, we need to see if he gave approval
//						if(localStorage.syncExams){
//							//if the user gave access - sync
//							if(window.bidit_globals.g_acsess){
//								deleteOldExamsAndSyncNew();
//							}
//							//if the user didn't give us his approval -
//							//tell the user he didn't give us his approval, so no sync accured.
//							else{
//								//to change the url to bid-it
//								}
//						}
//					}
//				});//ajax closed
//			}
//		});//ajax closed
//
//
//	}
//
//	function operateLogging(){
//		getLoginUrl();
//		localStorage.inWebsiteForTheFirstTime = "1";
//
//		localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
//		localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);
//
//		window.location.replace(window.bidit_globals.g_loginUrl);
//
//
//	}
//
//	$('#signInButtonMainScreen').click(function(){
//		if($('#signInButtonMainScreen').attr('name') == 'logout'){
//
//			if(typeof(Storage)!=="undefined"){
//
//				// show alert
//				if (localStorage.showLogoutAlert != '0' && (localStorage.isDataSaved_A == '0' || localStorage.isDataSaved_B == '0')){
//					$('#alertModal').attr('name','LOGOUT');
//					$('#neverShowAgainQuestAlert').prop('checked', false);
//					var message1 = 'האם ברצונך לשמור את המערכת לפני שאתה מתנתק?';
//					var message2 = 'שים לב: השמירה תתבצע עבור כל הסמסטרים';
//					var header1 = 'התנתקות';
//					$('#noAlert').show();
//					$('#yesAlert').show();
//					$('#cancelAlert').show();
//					$('#approveAlert').hide();
//					$('#alertContent').text(message1);
//					$('#alertQuestion').text(message2);
//					$('#alertHeader').text(header1);
//					$('#alertModal').modal('show');
//				}
//
//				// dont show alert
//				else{
//					FB.api("me/permissions","delete", function(response){/*do something if you want*/});
//					window.bidit_globals.g_facebookUserID = '';
//					operateLogging();
//				}
//			}
//			else{
//				$('neverShowAgainQuestAlertDiv').empty();
//			}
//		}
//
//		else{
//			window.location.replace(window.bidit_globals.g_loginUrl);
//		}
//	});
//
//	function showStoredScheduleData(){
//		var displaySettingsCookie = JSON.parse(localStorage.biditDisplaySettingsCookie);
//		var scheduleInfoCookie = JSON.parse(localStorage.biditScheduleInfoCookie);
//		var currSemesterStored = localStorage.currSemester;
//
//		var cookieScheduleObj = {};
//		cookieScheduleObj['coursesInfoArr'] = scheduleInfoCookie;
//		cookieScheduleObj['displaySettingsArr'] = displaySettingsCookie;
//		showLoadedSchedule(2);
//
//		if (currSemesterStored == 1){
//
//		}
//
//
//	}

	/*================================================================================================
	 *                                       Save Schedule 
	 *================================================================================================
	 */

//	$('#saveSemesterA').click(function(){
//		saveScheduleForUser(0);
//	});
//
//	$('#saveSemesterB').click(function(){
//		saveScheduleForUser(1);
//	});
//
//	$('#saveAllSemesters').click(function(){
//		saveScheduleForUser(2);
//	});
//
//	function whichCoursesAreInSchedule(){
//		var coursesArr = window.bidit_globals.g_coursesDisplaySettings;
//		var chosenScheduleCourses = [];
//		var chosenScheduleCoursesA = [];
//		var chosenScheduleCoursesB = [];
//		chosenScheduleCourses.push(chosenScheduleCoursesA);
//		chosenScheduleCourses.push(chosenScheduleCoursesB);
//
//
//		$.each(coursesArr[0],function(){
//			var isCourseChosen = this.cChosen;
//			var courseNum = this.course_num;
//			if(isCourseChosen){
//				chosenScheduleCourses[0].push(courseNum);
//			}
//		});
//
//		$.each(coursesArr[1],function(){
//			var isCourseChosen = this.cChosen;
//			var courseNum = this.course_num;
//			if(isCourseChosen){
//				chosenScheduleCourses[1].push(courseNum);
//			}
//		});
//
//		return chosenScheduleCourses;
//	}
//
//	function saveScheduleForUser(semesterToSave){
//		//Update cookies that user saved his changes
//		if(semesterToSave == 0){
//			localStorage.isDataSaved_A = '1';
//		}
//		else if(semesterToSave == 1){
//			localStorage.isDataSaved_B = '1';
//		}
//		else{
//			localStorage.isDataSaved_A = '1';
//			localStorage.isDataSaved_B = '1';
//		}
//
//
//		//Chosen courses in schedule
//		var chosenCourses = whichCoursesAreInSchedule();
//
//        var ajaxSavedData = [];
//        var ajaxScheduleToSaveObj = {};
//
//		ajaxScheduleToSaveObj['displaySettingsArr'] = window.bidit_globals.g_coursesDisplaySettings;
//		ajaxScheduleToSaveObj['coursesInfoArr'] = window.bidit_globals.g_allSemestersAccordions;
//
//		ajaxSavedData.push(window.bidit_globals.g_userID);
//		ajaxSavedData.push(window.bidit_globals.g_userEmail);
//		ajaxSavedData.push(window.bidit_globals.g_userNickName);
//		ajaxSavedData.push(ajaxScheduleToSaveObj);
//		ajaxSavedData.push(semesterToSave);
//		ajaxSavedData.push(chosenCourses);
//
//		requestAjax = $.ajax({
//			type: "POST",
//			url: "/ajax/saveUserData/",
//			data: JSON.stringify(ajaxSavedData),
//			success: function () {
//				showAlert('המערכת שלך נשמרה בהצלחה','warning');
//			}
//		});
//	}


	/*================================================================================================
	 *                                       Load Schedule
	 *================================================================================================
	 */

//    function semesterNotLoadedColorInit(semesterNum){
//		var semesterCoursesDisplayArr = window.bidit_globals.g_coursesDisplaySettings[semesterNum];
//
//		$.each(semesterCoursesDisplayArr, function(){
//			var courseObj = this;
//			var course_num = courseObj.course_num;
//			var cColor = courseObj.cColor;
//			if(courseObj.cChosen){
//				var colorIndex = window.bidit_globals.g_colorsStock.indexOf(cColor);
//
//				if(colorIndex != -1){
//					window.bidit_globals.g_colorsStock.splice(colorIndex, 1);
//					window.bidit_globals.g_scheduleColors.push(cColor);
//				}
//				// maybe we changed our colors
//				else{
//					var pickColor = window.bidit_globals.g_colorsStock.pop();
//					(window.bidit_globals.g_coursesDisplaySettings[semesterNum])[course_num].cColor = pickColor;
//				}
//
//			}
//		});
//	}
//
//	$('#loadSemesterA').click(function(){
//		loadScheduleForUser(0);
//	});
//
//	$('#loadSemesterB').click(function(){
//		loadScheduleForUser(1);
//	});
//
//	$('#loadAllSemesters').click(function(){
//		loadScheduleForUser(2);
//	});
//
//	function loadScheduleForUser(semesterToLoad){
//		requestAjax = $.ajax({
//			type: "GET",
//			url: "/ajax/loadUserData/",
//			dataType: 'json',
//			data: {'user_id': window.bidit_globals.g_userID,
//				'user_email': window.bidit_globals.g_userEmail,
//				'nick_name': window.bidit_globals.g_userNickName },
//				success: function () {
//					//%%FIX
//                    showLoadedSchedule(semesterToLoad);
//
//					showAlert('המערכת שלך נטענה בהצלחה','warning');
//				}
//		});
//	}
//
//    function showLoadedSchedule(semesterToLoad) {
//        clearTimetableView();
//
//		//Initializing colors
//		copyColorsArray();
//
//		//Initializing global arrays
//		window.bidit_globals.g_scheduleColors = [];
//
//		if(semesterToLoad != 2){
//			var semesterNotLoaded = getOtherSemester(semesterToLoad);
//			semesterNotLoadedColorInit(semesterNotLoaded);
//		}
//
//		//Update the current semester schedule and courses on screen
//		showCurrentCoursesAndSchedule();
//
//		//Update local storage with the latest data
//		localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
//		localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);
//	}
//

    /*================================================================================================
	 *                     				google calendar sync exams
	 *================================================================================================*/	

//	$('#SyncSemesterAExams').click(function(){
//		localStorage.semesterToSync = 0;
//		localStorage.syncExams = true;
//	});
//
//	$('#SyncSemesterBExams').click(function(){
//		localStorage.semesterToSync = 1;
//		localStorage.syncExams = true;
//	});
//
//	$('#SyncAllExams').click(function(){
//		localStorage.semesterToSync = 2;
//		localStorage.syncExams = true;
//	});
//
//	//delete old exams and sync new ones by user choice
//	function deleteOldExamsAndSyncNew(){
//		showAlert('מסנכרן מבחנים...','warning');
//		window.bidit_globals.g_examObj2 = window.bidit_globals.g_examObj;
//		//get all old event links from DS
//        $.ajax({
//            type: "GET",
//            url: "/ajax/getOldExamsLinks/",
//            dataType: 'json',
//            data: {'userId': window.bidit_globals.g_userID}, //%%
//            success: function (data) {
//                //an array of 3 arrays - old links of sem A, sem B and year
//                var oldExamsLinks = data.response;
//                //if chosen sem A => delete sem A and year courses, sync sem A and year courses, save new sem A links and year links to DB
//                if (localStorage.semesterToSync == 0) {
//                    syncSemAExams(oldExamsLinks);
//                }
//                //else if chosen sem B => delete sem B and year courses, sync sem A and year courses, save new sem B links and year links to DB
//                else {
//                    if (localStorage.semesterToSync == 1) {
//                        syncSemBExams(oldExamsLinks);
//                    }
//                    //else if chosen allSem => delete both semesters courses and year courses, sync both semesters and year courses, save new links to DB
//                    else {
//                        syncAllSemExams(oldExamsLinks);
//                    }
//                }
//            }
//        });
//	}
//
//	//delete add and save sem A and all year exams
//	function syncSemAExams(oldExamsLinks){
//		var oldExamsLinksSemA = oldExamsLinks[0].concat(oldExamsLinks[2]);
//		//if there are old events to delete => delete old events, add new ones and save to DB
//		if (oldExamsLinksSemA.length>0){
//			var numOfEventsToDelete = oldExamsLinksSemA.length;
//			var numOfEventsDeleted = 0;
//			$.each(oldExamsLinksSemA , function(){
//				var ToSend = [];
//				var requestType = 'deleteEvent';
//				ToSend.push(requestType);
//				ToSend.push(this);
//				$.ajax({
//					type: "POST",
//					url: "/",
//					dataType: 'json',
//					data: JSON.stringify(ToSend),
//					success: function () {
//						numOfEventsDeleted = numOfEventsDeleted+1;
//						//if deleted all old events => add new events and save to DB
//						if(numOfEventsDeleted == numOfEventsToDelete){
//							addSemAExams(oldExamsLinks[1]);
//						}
//					}
//				});
//			});
//		}
//		//if there are no old events to delete => add new ones and save to DB
//		else{
//			addSemAExams(oldExamsLinks[1]);
//		}
//	}
//
//	//add and save sem A exams
//	function addSemAExams(oldSemBExamsLinks){
//		var eventLinksToSave = [[],oldSemBExamsLinks,[]];
//		//if there are no new events to add => just save in DB
//		if(countNumberOfCoursesNeededToBeAdded()==0){
//			saveEventLinksToDB(eventLinksToSave);
//		}
//		//if there are new events to add => add and save events in DB
//		else{
//			var numOfEventsAdded = 0;
//			var numOfEventsToAdd = countNumberOfCoursesNeededToBeAdded();
//			//for every exam in list of exams to sync
//			$.each(window.bidit_globals.g_examObj2 , function() {
//				if(this[6] == 0 || this[6] == 2){
//					var courseSem = this[6];
//					//create data structure to send to request
//					var arrayToSend1 = [];
//					var requestType = 'createEvent';
//					arrayToSend1.push(requestType);
//					this[0] = printDate(this[0]);
//					arrayToSend1.push(this);
//					requestAjaxSync4 = $.ajax({
//						type: "POST",
//						url: "/",
//						dataType: 'json',
//						data: JSON.stringify(arrayToSend1),
//						success: function (data) {
//							if(data.response == -1){
//								showAlert('סינכרון \"'+data.msg+'\" לא הצליח','warning');
//								var stateObj = { obj: "URL" };
//								history.replaceState(stateObj, "page", "http://bid-it.appspot.com/");
//								var badURL = $('#SyncAllExams > a').attr('href');
//								var indexOfToken = badURL.toLowerCase().indexOf("token");
//								if (indexOfToken >= 0){
//									$('#SyncAllExams > a').attr('href',badURL.substring(0,indexOfToken));
//									$('#SyncSemesterAExams > a').attr('href',badURL.substring(0,indexOfToken));
//									$('#SyncSemesterBExams > a').attr('href',badURL.substring(0,indexOfToken));
//								}
//							}
//							else{
//								numOfEventsAdded = numOfEventsAdded+1;
//								eventLinksToSave[courseSem].push(data.response);
//								//if finished adding events => save to DB
//								if(numOfEventsToAdd == numOfEventsAdded){
//									saveEventLinksToDB(eventLinksToSave);
//								}
//							}
//						}
//					});
//				}
//			});
//		}
//	}
//
//	//delete add and save sem B and all year exams
//	function syncSemBExams(oldExamsLinks){
//		var oldExamsLinksSemB = oldExamsLinks[1].concat(oldExamsLinks[2]);
//		//if there are old events to delete => delete old events, add new ones and save to DB
//		if (oldExamsLinksSemB.length>0){
//			var numOfEventsToDelete = oldExamsLinksSemB.length;
//			var numOfEventsDeleted = 0;
//			$.each(oldExamsLinksSemB , function(){
//				var ToSend = [];
//				var requestType = 'deleteEvent';
//				ToSend.push(requestType);
//				ToSend.push(this);
//				requestAjaxSync5 = $.ajax({
//					type: "POST",
//					url: "/",
//					dataType: 'json',
//					data: JSON.stringify(ToSend),
//					success: function () {
//						numOfEventsDeleted = numOfEventsDeleted+1;
//						//if deleted all old events => add new events and save to DB
//						if(numOfEventsDeleted == numOfEventsToDelete){
//							addSemBExams(oldExamsLinks[0]);
//						}
//					}
//				});
//			});
//		}
//		//if there are no old events to delete => add new ones and save to DB
//		else{
//			addSemBExams(oldExamsLinks[0]);
//		}
//	}
//
//	//add and save sem B exams
//	function addSemBExams(oldSemAExamsLinks){
//		var eventLinksToSave = [oldSemAExamsLinks,[],[]];
//		//if there are no new events to add => just save in DB
//		if(countNumberOfCoursesNeededToBeAdded()==0){
//			saveEventLinksToDB(eventLinksToSave);
//		}
//		//if there are new events to add => add and save events in DB
//		else{
//			var numOfEventsAdded = 0;
//			var numOfEventsToAdd = countNumberOfCoursesNeededToBeAdded();
//			//for every exam in list of exams to sync
//			$.each(window.bidit_globals.g_examObj2 , function() {
//				if(this[6] == 1 || this[6] == 2){
//					var courseSem = this[6];
//					//create data structure to send to request
//					var arrayToSend1 = [];
//					var requestType = 'createEvent';
//					arrayToSend1.push(requestType);
//					this[0] = printDate(this[0]);
//					arrayToSend1.push(this);
//					requestAjaxSync6 = $.ajax({
//						type: "POST",
//						url: "/",
//						dataType: 'json',
//						data: JSON.stringify(arrayToSend1),
//						success: function (data) {
//							if(data.response == -1){
//								showAlert('סינכרון \"'+data.msg+'\" לא הצליח','warning');
//								var stateObj = { obj: "URL" };
//								history.replaceState(stateObj, "page", "http://bid-it.appspot.com/");
//								var badURL = $('#SyncAllExams > a').attr('href');
//								var indexOfToken = badURL.toLowerCase().indexOf("token");
//								if (indexOfToken >= 0){
//									$('#SyncAllExams > a').attr('href',badURL.substring(0,indexOfToken));
//									$('#SyncSemesterAExams > a').attr('href',badURL.substring(0,indexOfToken));
//									$('#SyncSemesterBExams > a').attr('href',badURL.substring(0,indexOfToken));
//								}
//							}
//							else{
//								numOfEventsAdded = numOfEventsAdded+1;
//								eventLinksToSave[courseSem].push(data.response);
//								//if finished adding events => save to DB
//								if(numOfEventsToAdd == numOfEventsAdded){
//									saveEventLinksToDB(eventLinksToSave);
//								}
//							}
//						}
//					});
//				}
//			});
//		}
//	}
//
//	//delete add and save all sem exams
//	function syncAllSemExams(oldExamsLinks){
//		var oldExamsLinksAllSem = oldExamsLinks[0].concat(oldExamsLinks[1],oldExamsLinks[2]);
//		//if there are old events to delete => delete old events, add new ones and save to DB
//		if (oldExamsLinksAllSem.length>0){
//			var numOfEventsToDelete = oldExamsLinksAllSem.length;
//			var numOfEventsDeleted = 0;
//			$.each(oldExamsLinksAllSem, function(){
//				var ToSend = [];
//				var requestType = 'deleteEvent';
//				ToSend.push(requestType);
//				ToSend.push(this);
//                $.ajax({
//                    type: "POST",
//                    url: "/",
//                    dataType: 'json',
//                    data: JSON.stringify(ToSend),
//                    success: function () {
//                        numOfEventsDeleted = numOfEventsDeleted + 1;
//                        //if deleted all old events => add new events and save to DB
//                        if (numOfEventsDeleted == numOfEventsToDelete) {
//                            addAllSemExams();
//                        }
//                    }
//                });
//			});
//		}
//		//if there are no old events to delete => add new ones and save to DB
//		else{
//			addAllSemExams();
//		}
//	}
//
//	//add and save all sem exams
//	function addAllSemExams(){
//		var eventLinksToSave = [[],[],[]];
//		//if there are no new events to add => just save in DB
//		if(countNumberOfCoursesNeededToBeAdded()==0){
//			saveEventLinksToDB(eventLinksToSave);
//		}
//		//if there are new events to add => add and save events in DB
//		else{
//			var numOfEventsAdded = 0;
//			var numOfEventsToAdd = countNumberOfCoursesNeededToBeAdded();
//			//for every exam in list of exams to sync
//			$.each(window.bidit_globals.g_examObj2 , function() {
//				var courseSem = this[6];
//				//create data structure to send to request
//				var arrayToSend1 = [];
//				var requestType = 'createEvent';
//				arrayToSend1.push(requestType);
//				this[0] = printDate(this[0]);
//				arrayToSend1.push(this);
//				requestAjaxSync8 = $.ajax({
//					type: "POST",
//					url: "/",
//					dataType: 'json',
//					data: JSON.stringify(arrayToSend1),
//					success: function (data) {
//						if(data.response == -1){
//							showAlert('סינכרון \"'+data.msg+'\" לא הצליח','warning');
//							var stateObj = { obj: "URL" };
//							history.replaceState(stateObj, "page", "http://bid-it.appspot.com/");
//							var badURL = $('#SyncAllExams > a').attr('href');
//							var indexOfToken = badURL.toLowerCase().indexOf("token");
//							if (indexOfToken >= 0){
//								$('#SyncAllExams > a').attr('href',badURL.substring(0,indexOfToken));
//								$('#SyncSemesterAExams > a').attr('href',badURL.substring(0,indexOfToken));
//								$('#SyncSemesterBExams > a').attr('href',badURL.substring(0,indexOfToken));
//							}
//						}
//						else{
//							numOfEventsAdded = numOfEventsAdded+1;
//							eventLinksToSave[courseSem].push(data.response);
//							//if finished adding events => save to DB
//							if(numOfEventsToAdd == numOfEventsAdded){
//								saveEventLinksToDB(eventLinksToSave);
//							}
//						}
//					}
//				});
//			});
//		}
//	}
//
//	//save event links list in DB
//	function saveEventLinksToDB(eventLinksToSave){
//		var arrayToSend = [];
//		arrayToSend.push(window.bidit_globals.g_userID);
//		arrayToSend.push(window.bidit_globals.g_userEmail);
//		arrayToSend.push(window.bidit_globals.g_userNickName);
//		arrayToSend.push(eventLinksToSave);
//        $.ajax({
//            type: "POST",
//            url: "/ajax/saveEventLinksToDS/",
//            dataType: 'json',
//            data: JSON.stringify(arrayToSend),
//            success: function () {
//                showAlert('המבחנים סונכרנו בהצלחה', 'warning');
//                localStorage.syncExams = false;
//                localStorage.semesterToSync = -1;
//                var stateObj = { obj: "URL" };
//                history.replaceState(stateObj, "page", "http://bid-it.appspot.com/");
//                var badURL = $('#SyncAllExams > a').attr('href');
//                var indexOfToken = badURL.toLowerCase().indexOf("token");
//                if (indexOfToken >= 0) {
//                    $('#SyncAllExams > a').attr('href', badURL.substring(0, indexOfToken));
//                    $('#SyncSemesterAExams > a').attr('href', badURL.substring(0, indexOfToken));
//                    $('#SyncSemesterBExams > a').attr('href', badURL.substring(0, indexOfToken));
//                }
//            }
//        });
//	}
//
//	//counts number of exams needed to be added
//	function countNumberOfCoursesNeededToBeAdded(){
//		var n = 0;
//        var allExams = window.bidit_globals.g_examObj2;
//        var chosenSem = localStorage.semesterToSync;
//		if(chosenSem==0){
//			$.each(allExams , function(){
//				if(this[6]==0 || this[6]==2){
//					n = n+1;
//				}
//			});
//		}
//		else{
//			if(chosenSem==1){
//				$.each(allExams , function(){
//					if(this[6]==1 || this[6]==2){
//						n = n+1;
//					}
//				});
//			}
//			else{
//				$.each(allExams , function(){
//					n = n+1;
//				});
//			}
//		}
//		return n;
//	}

	/*================================================================================================
	 *                                    Read More
	 *================================================================================================*/	


	$("#readMoreModal").on('shown', function (){
		$('#chooseCoursesStep').click();
	});

	$('#chooseCoursesStep').click(function(){
		$("#readMoreBody").animate({ scrollTop: 0}, 'fast');    

		$('#chooseCoursesStep').addClass('current');
		$('#catalogsStep').removeClass('current');
		$('#optimizeStep').removeClass('current');
		$('#extraStep').removeClass('current');
		$('#changesStep').removeClass('current');

		$('#stepChooseCourses').css("display","block");
		$('#stepCatalog').css("display","none");
		$('#stepOptimize').css("display","none");
		$('#stepExtra').css("display","none");
		$('#stepChanges').css("display","none");

		$('#chooseCoursesBadge').addClass('badge-inverse');
		$('#catalogBadge').removeClass('badge-inverse');
		$('#optimizeBadge').removeClass('badge-inverse');
		$('#extraBadge').removeClass('badge-inverse');
		$('#changesBadge').removeClass('badge-inverse');

	});	

	$('#catalogsStep').click(function(){
		$("#readMoreBody").animate({ scrollTop: 0}, 'fast');    

		$('#chooseCoursesStep').removeClass('current');
		$('#catalogsStep').addClass('current');
		$('#optimizeStep').removeClass('current');
		$('#extraStep').removeClass('current');
		$('#changesStep').removeClass('current');

		$('#stepChooseCourses').css("display","none");
		$('#stepCatalog').css("display","block");
		$('#stepOptimize').css("display","none");
		$('#stepExtra').css("display","none");
		$('#stepChanges').css("display","none");

		$('#chooseCoursesBadge').removeClass('badge-inverse');
		$('#catalogBadge').addClass('badge-inverse');
		$('#optimizeBadge').removeClass('badge-inverse');
		$('#extraBadge').removeClass('badge-inverse');
		$('#changesBadge').removeClass('badge-inverse');
	});

	$('#optimizeStep').click(function(){
		$("#readMoreBody").animate({ scrollTop: 0}, 'fast');     

		$('#chooseCoursesStep').removeClass('current');
		$('#catalogsStep').removeClass('current');
		$('#optimizeStep').addClass('current');
		$('#extraStep').removeClass('current');
		$('#changesStep').removeClass('current');

		$('#stepChooseCourses').css("display","none");
		$('#stepCatalog').css("display","none");
		$('#stepOptimize').css("display","block");
		$('#stepExtra').css("display","none");
		$('#stepChanges').css("display","none");

		$('#chooseCoursesBadge').removeClass('badge-inverse');
		$('#catalogBadge').removeClass('badge-inverse');
		$('#optimizeBadge').addClass('badge-inverse');
		$('#extraBadge').removeClass('badge-inverse');
		$('#changesBadge').removeClass('badge-inverse');

	});	

	$('#extraStep').click(function(){
		$("#readMoreBody").animate({ scrollTop: 0}, 'fast');     

		$('#chooseCoursesStep').removeClass('current');
		$('#catalogsStep').removeClass('current');
		$('#optimizeStep').removeClass('current');
		$('#extraStep').addClass('current');
		$('#changesStep').removeClass('current');

		$('#stepChooseCourses').css("display","none");
		$('#stepCatalog').css("display","none");
		$('#stepOptimize').css("display","none");
		$('#stepExtra').css("display","block");
		$('#stepChanges').css("display","none");

		$('#chooseCoursesBadge').removeClass('badge-inverse');
		$('#catalogBadge').removeClass('badge-inverse');
		$('#optimizeBadge').removeClass('badge-inverse');
		$('#extraBadge').addClass('badge-inverse');
		$('#changesBadge').removeClass('badge-inverse');

	});	

	$('#changesStep').click(function(){
		$("#readMoreBody").animate({ scrollTop: 0}, 'fast');    

		$('#chooseCoursesStep').removeClass('current');
		$('#catalogsStep').removeClass('current');
		$('#optimizeStep').removeClass('current');
		$('#extraStep').removeClass('current');
		$('#changesStep').addClass('current');

		$('#stepChooseCourses').css("display","none");
		$('#stepCatalog').css("display","none");
		$('#stepOptimize').css("display","none");
		$('#stepExtra').css("display","none");
		$('#stepChanges').css("display","block");

		$('#chooseCoursesBadge').removeClass('badge-inverse');
		$('#catalogBadge').removeClass('badge-inverse');
		$('#optimizeBadge').removeClass('badge-inverse');
		$('#extraBadge').removeClass('badge-inverse');
		$('#changesBadge').addClass('badge-inverse');

	});

	$('#nextStep1').click(function(){
		$('#catalogsStep').click();
	});

    $('#prevStep1').click(function(){
	});

	$('#nextStep2').click(function(){
		$('#optimizeStep').click();
	});

    $('#prevStep2').click(function(){
		$('#chooseCoursesStep').click();
	});

    $('#nextStep3').click(function(){
		$('#changesStep').click();
	});

    $('#prevStep3').click(function(){
		$('#catalogsStep').click();
	});

    $('#nextStep4').click(function(){
		$('#extraStep').click();
	});

    $('#prevStep4').click(function(){
		$('#optimizeStep').click();
	});

	$('#nextStep5').click(function(){

	});

    $('#prevStep5').click(function(){
		$('#changesStep').click();
	});

	/*================================================================================================
	 *                                       ALERT MODAL HANDLE
	 *================================================================================================*/

	$('#neverShowAgainQuestAlert').change(function() {
        var operationName;
        if ($("#neverShowAgainQuestAlert").is(':checked')) {
			operationName =  $('#alertModal').attr('name');
			switch (operationName){
			case 'LOGOUT': 		localStorage.showLogoutAlert = '0';
			break;
			}
		}
		else {
			operationName =  $('#alertModal').attr('name');
			switch (operationName){
			case 'LOGOUT': 		localStorage.showLogoutAlert = '1';
			break;
			}
		}
	});

	$('#cancelAlert').click(function(){
		$('#alertModal').modal('hide');

		var operationName =  $('#alertModal').attr('name');
		switch (operationName){
		case 'LOGOUT':
			break;
		}
	});

	$('#yesAlert').click(function(){
		$('#alertModal').modal('hide');

		var operationName =  $('#alertModal').attr('name');
		switch (operationName){
		case 'LOGOUT':  saveScheduleForUser(2);
		FB.api("me/permissions","delete", function(response){/*do something if you want*/});
		window.bidit_globals.g_facebookUserID = '';
		operateLogging();
		break;
		}
	});

	$('#noAlert').click(function(){
		$('#alertModal').modal('hide');

		var operationName =  $('#alertModal').attr('name');
		switch (operationName){
		case 'LOGOUT': FB.api("me/permissions","delete", function(response){/*do something if you want*/});
		window.bidit_globals.g_facebookUserID = '';
		operateLogging();
		break;
		}
	});

	/*================================================================================================
	 *                                      html2canvas 
	 *================================================================================================
	 */

	$('.navbar').load(function(){
		clearTimetableView();
		updateTimeTableView();
	});

	function captureTT(isColor){

		if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1)
		{
			$('html').css("max-width","900px");
		}
		{
			window.bidit_globals.g_printRes = $(window).width();
			$('html').width(900);
		}
		$('#examsForPrint').css("max-height","");

		$('#timeTable').removeClass('table-striped');

		/*in case of IE add the borders of the table*/
		if (!(/msie/.test(navigator.userAgent.toLowerCase()))){
			//$('#timeTable').attr('border','1');
		}

		$('#ttHead').removeClass('info');
		colorHeaders();

		$('.navbar').addClass('hide');
		$('.tabbable').addClass('hide');
		$('#accordionParentDiv').addClass('hide');
		$('#search').addClass('hide');
		$('#optimizeButtons').addClass('hide');
		$('#hoursDiv').addClass('hide');
		$('#chooseCoursesBlueBtn').addClass('hide');
		$('#rightFooterAreatStrip').addClass('hide');
		/**/

		$('#examsHeader').addClass('hide');
		//$('#examsHeaderWhite').addClass('hide');
		$('#ExclamationDiv').addClass('hide');
		$('#examsForPrint').addClass('hide');
		$('#lowerWide').css("max-width","900px");

		/**/
		$('#calendarStrip').addClass('hide');
		$('#footerAreaPrinting').addClass('hide');		
		$('#alertsArea').css("display","none");

		$('#backFromPrint').removeClass('hide');
		$('#mailPrint').removeClass('hide');
		$('#printPrint').removeClass('hide');

		$('#html2canvasArea').empty();



		$('#backFromPrint').addClass('hide');
		$('#mailPrint').addClass('hide');
		$('#printPrint').addClass('hide');
		$('#goToPrint').addClass('hide');


		enlargeTT();
		// Updating group selections on schedule
		clearTimetableView();
		updateTimeTableView();

		/*format the colors and the borders of the printed TT. parameter is true if coor and false for white*/
		whiteTT(isColor);

		//
		for (var i=1 ; i<$('.ttClass').length + 1 ; i++){
			$('.ttClass:nth-child('+i+')').text(function(){
				//save the old one in global
				return removeBraces($('.ttClass:nth-child('+i+')').text());

			});

		}

		canvasFunc();



	}

	function restoreTT(){
		$('html').width(window.bidit_globals.g_printRes);
		if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1)
		{
			$('html').css("max-width","");
		}
		$('#examsForPrint').css("max-height","233px");
		restoreBullets();
		$('#timeTable').addClass('table-striped');	
		$('#ttHead').addClass('info');
		uncolorHeaders();
		$('#tableRF').removeClass('hide');
		$('.navbar').removeClass('hide');
		$('.tabbable').removeClass('hide');
		$('#accordionParentDiv').removeClass('hide');
		$('#search').removeClass('hide');
		$('#optimizeButtons').removeClass('hide');
		$('#hoursDiv').removeClass('hide');
		$('#chooseCoursesBlueBtn').removeClass('hide');
		$('#rightFooterAreatStrip').removeClass('hide');
		$('#examsHeader').removeClass('hide');
		$('#examsHeaderWhite').addClass('hide');
		$('#ExclamationDiv').removeClass('hide');
		$('#examsForPrint').removeClass('hide');
		$('#lowerWide').css("max-width","");
		$('#calendarStrip').removeClass('hide');
		$('#footerAreaPrinting').removeClass('hide');


		$('#alertsArea').css("display","block");

		$('#backFromPrint').addClass('hide');
		$('#mailPrint').addClass('hide');
		$('#printPrint').addClass('hide');

		$('#html2canvasArea').addClass('hide');



		$('#detailsForPrint').css("display","none");
		$('#detailsForPrint').addClass('hide');
		//$('#detailsForPrint').empty();

		window.bidit_globals.g_printOnlyCurrSem = false;
		updateExamsAndCalendar();
		diminishTT();
		restoreWhiteTT();
		// Updating group selections on schedule
		clearTimetableView();
		updateTimeTableView();


	}

	function canvasFunc(){
		if(jQuery.browser.name.toLowerCase() == 'firefox'){
			html2canvas(document.body, {
				onrendered: function(canvas) {
					canvasFuncHelper(canvas);
				},
				letterRendering: true,
				height: 750,
				width: 880
			});	
		}
		else {
			html2canvas(document.body, {
				onrendered: function(canvas) {
					canvasFuncHelper(canvas);
				},
				letterRendering: true,
				height: 750
			});	
		}
	}

	$('#printFromPrint').click(function(){
		window.print();
		restoreTT();
		$('#goToPrint').removeClass('hide');
	});
	
	$('#goBackFromPrint').click(function(){
		restoreTT();
		$('#goToPrint').removeClass('hide');
	});

    function canvasFuncHelper(canvas) {
        document.getElementById('html2canvasArea').appendChild(canvas);
		//  $('#html2canvasArea').append(canvas);
		//document.body.appendChild(canvas);
		//$('#html2canvasArea').css("margin-bottom","-200px");
		$('#html2canvasArea').removeClass('hide');
		$('#examsHeader').addClass('hide');
		$('#examsHeaderWhite').removeClass('hide');
		/**/
		//$('#ExclamationDiv').removeClass('hide');
		$('#examsForPrint').removeClass('hide');
		$('#examsForPrint').css("max-height","20000px");
		window.bidit_globals.g_printOnlyCurrSem = true;
		updateExamsAndCalendar();
		/**/
		$('#tableRF').addClass('hide');

		$('#backFromPrint').removeClass('hide');
		$('#mailPrint').removeClass('hide');
		$('#printPrint').removeClass('hide');
		$('#detailsForPrint').removeClass('hide');
		$('#detailsForPrint').css("display","inline-block");
		
		changePrintButtonsLocation();
		/*
		$('#detailsForPrint').empty();
		$('#detailsForPrint').append(function(){
			return '<img src="assets/img/logo-black.jpg"  />'+
			'<button id="goBackFromPrint" class="btn btn-info btn-medium noPrint">חזרה</button>';
		});
		*/
		

		hideBullets();

	}

	$('#goToPrintColor').click(function(){
		captureTT(true);
	});

	$('#goToPrintWhite').click(function(){
		captureTT(false);
	});

    function hideBullets(){
		$(".bulletSym").addClass('hide');
	}

	function restoreBullets(){
		$(".bulletSym").removeClass('hide');
	}

	function whiteTT(isColor){
		$('.ttClass').css('border','2px solid black');
		$('#timeTable > tbody > tr > td').css('border','2px solid #BDBDBD','!important');
		var oldWidth;
		var newWidth;
		var oldHeight;
		var newHeight;

        $('.ttClass').each(function () {
            oldWidth = $(this).width();
			newWidth = oldWidth * 0.98;
			$(this).width(newWidth);

			oldHeight = $(this).height();
			newHeight = oldHeight * 0.98;
			$(this).height(newHeight);


			$(this).css("margin-top","-2px","!important");
		});

		if (isColor == false){
			$('.ttClass').css("background-color","white");
			$('.ttClass').css("color","black");
			$('.ttClass').css("opacity","1");
			$('.ttClass').css("filter","");

			$('.ttClassColor').css("background-color","white");
			$('.ttClassColor').css("color","black");
			$('.ttClassColor').css("opacity","1");
			$('.ttClassColor').css("filter","");
		}
	}

	function restoreWhiteTT(){
		/*switch classes for no color*/

		$('.ttClass').css("background-color","");
		$('.ttClass').css("color","");
		$('.ttClass').css("opacity","0.8");
		$('.ttClass').css("filter","alpha(opacity =       80)");

		$('.ttClassColor').css("background-color","");
		$('.ttClassColor').css("color","");
		$('.ttClassColor').css("opacity","0.8");
		$('.ttClassColor').css("filter","alpha(opacity =       80)");	

		$('#timeTable > tbody > tr > td').css('border','');

		// Updating group selections on schedule
		clearTimetableView();
		updateTimeTableView();
	}

	function enlargeTT(){
		$('#timeTable > tbody > tr').css("height","45px");
		$('#timeTable').css("width","900px");
		$('#timeTable').css("margin-right","-192px");
	}

	function diminishTT(){
		$('#timeTable > tbody > tr').css("height","");
		$('#timeTable').css("width","");
		$('#timeTable').css("margin-right","");
	}

	function colorHeaders(){
		var backCol = "#EEE";
		$('#ttHead').css("background-color",backCol);
		$('#hour08').css("background-color",backCol);
		$('#hour09').css("background-color",backCol);
		$('#hour10').css("background-color",backCol);
		$('#hour11').css("background-color",backCol);
		$('#hour12').css("background-color",backCol);
		$('#hour13').css("background-color",backCol);
		$('#hour14').css("background-color",backCol);
		$('#hour15').css("background-color",backCol);
		$('#hour16').css("background-color",backCol);
		$('#hour17').css("background-color",backCol);
		$('#hour18').css("background-color",backCol);
		$('#hour19').css("background-color",backCol);
		$('#hour20').css("background-color",backCol);
		$('#hour21').css("background-color",backCol);
	}

	function uncolorHeaders(){
		$('#ttHead').css("background-color","");
		$('#hour08').css("background-color","");
		$('#hour09').css("background-color","");
		$('#hour10').css("background-color","");
		$('#hour11').css("background-color","");
		$('#hour12').css("background-color","");
		$('#hour13').css("background-color","");
		$('#hour14').css("background-color","");
		$('#hour15').css("background-color","");
		$('#hour16').css("background-color","");
		$('#hour17').css("background-color","");
		$('#hour18').css("background-color","");
		$('#hour19').css("background-color","");
		$('#hour20').css("background-color","");
		$('#hour21').css("background-color","");
	}

	function removeBraces(input){

		var first = -1;
		var last = -1;
		for (var i=input.length-1 ; i>0 ; i--){
			if (input[i]==")" || input[i]=="("){
				if (last == -1) {
					last=i;
					continue;
				}
				if (first == -1){
					first=i;
					continue;
				}
			}
		}
		if (first>-1 && last>-1) {
			var retStr = '';
			retStr += input.substring(0,first);
			retStr += '\n)';
			retStr += input.substring(first+1,last);
			retStr += input.substring(last+1,input.length);
			retStr += '(';
			return retStr;

		}
		return input;
	}
	
	function changePrintButtonsLocation(){
		var currWidth = $(window).width();

		if (currWidth > 900)
		{
			$('#printButtonsInPrint').css('right','796px');
			$('#printButtonsInPrint').css('left','');
		}
		
		else {
			$('#printButtonsInPrint').css('right','');
			$('#printButtonsInPrint').css('left','2%');
		}

	}

	/*================================================================================================
	 *                             Courses Popularity (Course Profile Screen)
	 *================================================================================================
	 */

//	$('#popularityMainDiv').delegate('#loginFromPopularity','click',function(){
//		localStorage.courseProfileFacebook = window.bidit_globals.g_currCourseProfile;
//		operateLogging();
//	});
//
//	$('#popularityTab').click(function(){
//		var hasClassDis = $(this).hasClass('facebookTabBtnDisabled');
//		if(hasClassDis == false){
//			$('#popularityTab').addClass('facebookTabBtnDisabled');
//			updatePopularityTab(true);
//		}
//	});
//
//	$('body').delegate('li[id^="friendCourse"]','mouseenter',function(){
//		$(this).unbind('click');
//		$(this).on('click', function(){
//			$('#courseProfileModal').modal('hide');
//			window.bidit_globals.g_currCourseProfile = ($(this).attr('id')).substring(12);
//			window.bidit_globals.g_currChosenInfoBtnFaculty = window.bidit_globals.g_currCourseProfile.substring(0,2);
//			window.bidit_globals.g_isProfileOpenedFromMain = true;
//
//			$('#tab3x').empty();
//			syllabusRequestAjax = $.ajax({ //%%
//				type: "GET",
//				url: "/ajax/get-syllabus/",
//				dataType: 'json',
//				data: {'semester': (window.bidit_globals.g_currSemester+1),//%%
//					'course_num': window.bidit_globals.g_currCourseProfile },
//					success: function(data)
//					{
//						syllabusRequestAjax = null; //%%
//						showCourseSyllabus(data);
//					}
//			});//ajax closed
//
//
//            $.when(getCurrentCourseFromAjax()).done(function (a6) {
//                courseProfileInit();
//				window.setTimeout(unAssignCourseProfileData,1000);
//				window.setTimeout(function(){
//					checkIfCanAssignProfileData(a6);
//				},1000);
//				window.setTimeout(function(){
//					$('#courseProfileModal').modal('show');
//				},1002);
//			});
//		});
//	});


	/****************end of main function******************/
});

